Working with EntityFramework and Ninject i need to dispose the context each time a call to a repository is finished. I need that so each time, a new call to the database is made, instead of using the EF context scope.
Here is my repository for testing:
public class VehicleRepositoryTest : IVehicleRepository
{
private DBEntities _context;
public VehicleRepositoryTest(DBEntities context)
{
_context = context;
}
....
public List<TB_VEHICULO> GetAll()
{
return _context.TB_VEHICULO.ToList();
}
And here is how i implement the ninject module. I use "IntransientScope" with the idea of disposing the context after each call:
Kernel.Bind<DBEntities>().ToSelf().InTransientScope();
Kernel.Bind<IVehicleRepository>().To<Test.VehicleRepositoryTest>().InTransientScope();
The idea is that each time a call "GetAll()" a new context is created, so each time a call to database is made.
But it is not working. If i make a call to "GetAll()", and supose i get data A; then i change in database data A to data B, make a new call to "GetAll()", i still getting data A.
More Info:
My application is a WinForms application, to call the instantiate the injected objects i use the composition pattern:
public static class CompositionRoot
{
public static IKernel kernel { get; private set; }
public static void WireModule(INinjectModule module)
{
kernel = new StandardKernel(module);
}
public static T Resolve<T>()
{
return kernel.Get<T>();
}
}
and the call to the repository is like this:
_vehicleRepository = CompositionRoot.Resolve<IVehicleRepository>();
var test = _vehicleRepository.GetAll();
I was with the same problem.
My old code:
kernel.Bind(typeof(IUnitOfWork)).To<UnitOfWork>().WithConstructorArgument("context", kernel.Get<MyContext>());
My new Code:
kernel.Bind<DbContext>().To<MyContext>();
kernel.Bind(typeof(IUnitOfWork)).To<UnitOfWork>();
This work to me.
Related
I am working on a big project that 80% completed (Some features need to be implemented though).But recently we discovered that the project doesn't allow concurrent requests (I mean multiple users request to same repository). Sometime we get null referece & sometimes "Executed can not open available connection , connection state is closed" etc.
Our source code is strongly restricted outside of the world. Here is some code.Let me know if there is any architectural problem, as architectural guys left company. It's using ninject 3.0. I already used InRequestScope() for all manager's repositories but no luck
Update: I am not using any ORM here, I am trying to connect SqlServer through data adapter in my DbContext class
public class DbContext
{
//execute query , nonquery etc using adapter & datatable
//Example
var dt=new DataTable();
_adapter=new _dbfactory.CreateAdapter();
_adapter.Fill(dt);
return dt;
}
//MyController
public class MyController
{
private readonly IMyManager_iMyManager;
public MyController(IMyManager iMyManager){_iMyManager=iMyManager}
public ActionResult Save()
{
_iMyManager.Save()
}
}
// My Manager
public class MyManager:IMyManager
{
private readonly IMyRepository _iMyRepository;
DbContext _dbContext=new
DbContext("someParameter","connectionstring");
public MyManager
(
IMyRepository iMyRepository, DbContext dbContext
)
{
_iMyRepository=iMyRepository;
_dbContext=dbContext;
}
Public DataTable GetDataTable()
{
try
{
_dbContext.Open();
_iMyRepository.GetDataTable()
}
catch(Exception ex){}
finally{_dbContext.Close()}
}
}
// here is the repository
Public class MyRepository:IMyRepository
{
public _dbContext;
public MyRepository(DbContext dbContext)
{
_dbContext=dbContext;
}
public DataTable GetDataTable()
{ return _dbContext.ExecuteQuery()}
}
Finally Here is our ninject binding
public class NinjectDependencyResolver()
{
var context=new DbContext("someparameter","connectionStrin");
kernel.Bind<IMyManager>().To<MyManager>().WithConstructorArgument("_dbContext",context);
kernel.Bind<IMyRepository >().To<MyRepository >().WithConstructorArgument("_dbContext",context);
}
there can have some typo in my code as I wrote everything in so editor
I think you did this too complicated in Ninject Dependency Resolver.
You shouldn't create DbContext with a new keyword. Instead you should make Ninject to be resolving DbContext in request scope or in thread scope.
To register DbContext you can do it like this:
kernel.Bind<DbContext>().To<MyDbContext>().WithConstructorArgument("someArgument", "someValue").InRequestScope();
kernel.Bind<IMyManager>().To<MyManager>().InRequestScope();
kernel.Bind<IMyRepository>().To<MyRepository>().InRequestScope();
You don't need to precise the constructor argument to DbContext as DbContext is only once registered in the Ninject.
You can also register DbContext to a DbContextProvider class and there you can add some specific logic to resolve object.
Example:
kernel.Bind<DbContext>().ToProvider<MyDbContextProvider>().InRequestScope();
internal class MyDbContextProvider : Ninject.Activation.IProvider
{
public object Create(IContext context)
{
return new MyDbContext("connectionStringArgument";
}
public Type Type { get { return typeof (MyDbContext); } }
}
I hope this helps.
You need to remove this initialization in the MyManager since you pass the initialized DbContext via IoC.
DbContext _dbContext=new
DbContext("someParameter","connectionstring");
You also need to remove the finally block in the GetDataTable in the MyManager class since as a rule of thumb, if the object is initialized via IoC, it should be destroyed by IoC as well.
finally{_dbContext.Close()}
If you are initializing something in the field level then why would you initialize it again from the constructor?
private readonly IMyRepository _iMyRepository;
DbContext _dbContext=new DbContext("someParameter","connectionstring");
public MyManager(IMyRepository iMyRepository, DbContext dbContext)
{
_iMyRepository=iMyRepository;
_dbContext=dbContext;
}
This may also be a typo. Either remove the _dbContext initialization from the constructor or delegate the task of initialization to the caller of this class.
Multiple initialization can also be the problem. since you are doing dbcontext initialization both in NinjectDependencyResolver() and MyManager. For this you are getting two different exceptions. This is a platform design issue i guess
Two problems:
// My Manager
public class MyManager:IMyManager
{
private readonly IMyRepository _iMyRepository;
DbContext _dbContext=new
DbContext("someParameter","connectionstring");
public MyManager
(
IMyRepository iMyRepository, DbContext dbContext
)
{
_iMyRepository=iMyRepository;
_dbContext=dbContext;
}
The new that is created for the field will be overwritten when the constructor is called.
public class NinjectDependencyResolver()
{
var context=new DbContext("someparameter","connectionStrin");
kernel.Bind<IMyManager>().To<MyManager>().WithConstructorArgument("_dbContext",context);
kernel.Bind<IMyRepository >().To<MyRepository >().WithConstructorArgument("_dbContext",context);
}
You create the context here once and pass it to each object creation. So you are still reusing the context object instead of creating it for each request scope.
I want to access some data within my overriden SaveChanges() in my dbcontext without passing any parameters. Any suggestions? I'm working with MVC4 and Entity Framework Database-First.
public partial class Entities : DbContext
{
public override int SaveChanges()
{
// i want to get user info from MVC model but no need to pass any parameters when call SaveChanges()
var UserInfo = userInfo;
// Call the original SaveChanges(), which will save both the changes made and the audit records
return base.SaveChanges();
}
}
Solution 1: Dependency Injection
This solution is pretty extensible, but you would have to modify the code in your repositories and controllers to use the injected dependencies instead of creating new instances with new.
Install Ninject. In Visual Studio, find the Package Manager Console and run Install-Package Ninject.MVC4 -dependencyVersion Highest in there.
Add constructor injection. Modify your controller, so that it gets an instance of your repository in its constructor. Modify your repository, so that it gets an instance of your entity context in its constructor. Cache your dependencies in private fields. Example code:
// In your controller:
public MyController(MyRepository repo)
{
this.repo = repo;
}
// In your repository:
public MyRepository(Entities context)
{
this.context = context;
}
// In your entities:
public Entities(UserInfo userInfo)
{
this.userInfo = userInfo;
}
Add a UserInfo provider. We need to tell Ninject where to get the UserInfo from. We can use the provider interface here:
public class UserInfoProvider : Provider<UserInfo>
{
protected override UserInfo CreateInstance(IContext context)
{
UserInfo UserInfo = new UserInfo();
// Do some complex initialization here.
return userInfo;
}
}
Add bindings. We need to tell Ninject to use the provider. We also want the lifetime of a UserInfo instance and of our entity context to be bound to the request cycle of MVC. Update your App_Start\NinjectWebCommon.cs:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<Entities>()
.ToSelf()
.InRequestScope();
kernel.Bind<UserInfo>()
.ToProvider<UserInfoProvider>()
.InRequestScope();
}
Run your app. Ninject should use your constructors and provide the requested dependencies.
For further information, visit the Ninject Wiki.
Solution 2: Thread local context
This requires no modification to your repositories, but it makes the code less testable and resembles an anti pattern somehow. This won't work if your controller calls multithreaded code.
Add context class.
public class UserInfoContext : IDisposable
{
private static readonly ThreadLocal<UserInfo> UserInfos = new ThreadLocal<UserInfo>();
public static UserInfo Current
{
get
{
if (UserInfos == null)
{
throw new InvalidOperationException("UserInfoContext has not been set.");
}
return UserInfos.Value;
}
}
public static UserInfoContext Create(UserInfo userInfo)
{
if (userInfo == null)
{
throw new ArgumentNullException("userInfo");
}
if (UserInfos.Value != null)
{
throw new InvalidOperationException("UserInfoContext should not be nested.");
}
UserInfos.Value = userInfo;
return new UserInfoContext();
}
private UserInfoContext() { }
public void Dispose()
{
UserInfos.Value = null;
}
}
Wrap your controller code. Example:
public ActionResult Index()
{
using (UserInfoContext.Create(myUserInfo))
{
// do stuff that calls your repositories
return View();
}
}
Update your Entities class.
public partial class Entities : DbContext
{
public override int SaveChanges()
{
var UserInfo = UserInfoContext.Current;
// Call the original SaveChanges(), which will save both the changes made and the audit records
return base.SaveChanges();
}
}
I am currently working on a project with has a console app and few library projects. One library project is a EF code first project which contains my models and the context:
public class MyDbContext: DbContext
{
public MyDbContext() : base("MyConnectionString")
{
}
public DbSet<File> Files { get; set; }
}
I also have a singleton class through which I want to access the database. The singleton looks like this:
public sealed class DbLogger : IDbLogger
{
private static readonly DbLogger instance = new DbLogger();
private static MyDbContext ctx = new MyDbContext();
static DbLogger() {
Database.SetInitializer<MyDbContext>(new DbInitializer());
}
private DbLogger() { }
public static DbLogger Instance
{
get {
return instance;
}
}
public void AddFile(string fileName)
{
ctx.Files.Add(new File() { FullPath = fileName });
}
}
The db initializer is very simple and just implements the CreateDatabaseIfNotExists. Nothing is done in Seed yet.
In the console all which references the library project I just want to use it as:
private DbLogger logger = DbLogger.Instance;
and call the logger from a Task using:
logger.AddFile("myFileName");
When the app gets to logger.AddFile call I get the following exception:
An exception of type 'System.InvalidOperationException' occurred in
EntityFramework.dll but was not handled in user code
Additional information: The context cannot be used while the model is
being created. This exception may be thrown if the context is used
inside the OnModelCreating method or if the same context instance is
accessed by multiple threads concurrently. Note that instance members
of DbContext and related classes are not guaranteed to be thread safe.
How can I delay the using of the context until the model was created?
I am currently a bit stuck with this and any idea on how to solve this would be appreciated.
Thank you!
I recommend this approach
public void AddFile(string fileName){
using(var ctx = new MyDbContext() ){
ctx.Files.Add(new File() { FullPath = fileName });
ctx.SaveChanges();
}
}
You should only use the DbContext when needed. Open the DB connection, interact with the DB and close the connection. The using statement take care of the opening and closing of the DB connection.
EDIT - updated with SaveChanges()
ad to #Kunukn answer:
I think that you should blame
private static MyDbContext ctx = new MyDbContext();
It was trying to acces context before database initializer run.
If you don't wan't to create new context on every AddFile() call, try create context in static constructor.
I see problem with line
Database.SetInitializer(new DbInitializer());
if you use
public void AddFile(string fileName){
using(var ctx = new MyDbContext() ){
ctx.Files.Add(new File() { FullPath = fileName });
ctx.SaveChanges();
}
}
then your purpose of singleton is not getting solved because it will create a new MyDbContext every time AddFile is called ( and this is recommended)
but even if you insist on having a single dbcontext object then you should create some
initialization fucntion and might be call it after object is created.
might be something like
private DbLogger logger = DbLogger.Instance;
logger.Initialize()
I have a problem with EF5. I am using MVC 4.5
I am trying to make the 1 context per request "pattern".
I am not using "unit of work" pattern, nor testing or DI.
I am using the Generic Repository pattern to interact with DB. Each repository uses the same context mantained by a singleton "DataContextManager".
In each request in the global asax I refresh the context, but something wrong is happening: ie: I have a paged list and moving by the pages if i change data in DB manualy it doesnt refresh correctly. It's not an HTML cache issue, i tested it.
I know is a EF Context problem because i have "something like this":
private static Context C; //for the singleton. And in global.asax
public Application_BeginRequest()
{
DataContextManager.RefreshNew();
}
protected void Application_EndRequest(object sender, EventArgs e)
{
Domain.DataContextManager.Dispose();
}
And the first time the list works and in the second page i get an error saying that the
Context is disposed.
I read something of using the context in Static variables, but i don't know whats happening. I would like to use something simple like this, because to implement the UnitOfWork pattern i will need to change a lot of code.
Here is a little snnipet of my classes:
public class DataContextManager
{
private static Entities _Context;
private const string ConnectionString = "connString";
public static Entities Context
{
get
{
if (DataContextManager._Context == null)
DataContextManager._Context = new Entities(ConfigurationManager.ConnectionStrings[ConnectionString].ConnectionString);
return DataContextManager._Context;
}
}
//This method is not necessary but made it for testing
public static void RefreshNew()
{
DataContextManager._Context = new Entities(ConfigurationManager.ConnectionStrings[ConnectionString].ConnectionString);
}
public static void Dispose()
{
if (DataContextManager._Context != null)
{
DataContextManager._Context.Dispose();
DataContextManager._Context = null;
}
}
}
And repositories use DataContextManager like this:
public class BaseRepository<TEntity> where TEntity : class
{
internal Entities context;
internal DbSet<TEntity> dbSet;
public BaseRepository()
: this(DataContextManager.Context)
{
}
public BaseRepository(Entities context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
Thanks in advance!
Pablo.
I don't know that you really need the manager class, since everything seems to just access the DbContext property.
That being said, you should normally avoid using DbContext in a static class; I don't have any canonical source to back that up, but my personal experience has been that it at some point causes more problems than any benefit having a static class provides. So, I'd update the manager like so:
public class DataContextManager
{
private readonly string connectionToUse = string.Empty;
private Entities _context;
public Entities Context
{
get
{
if (_context == null)
{
_context = new Entities(WebConfigurationManager.ConnectionStrings[connectionToUse].ConnectionString);
}
return _context;
}
}
public DataContextManager()
{
connectionToUse = "connString";
}
public DataContextManager(string key)
{
connectionToUse = key;
}
#region IDisposable Members
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposeAll)
{
if (disposeAll)
{
_context.Dispose();
}
_context = null;
}
#endregion
}
Then you simply add a protected field to each of your controllers and instantiate the manager in the controller's constructor:
protected DataContextManager Manager = null;
public HomeController()
{
Manager = new DataContextManager();
// or
//
//__manager = new DataContextManager("connection-To-Use");
}
If all of your controllers use the same DbContext class, you could create a BaseController class that inherits System.Web.Mvc.Controller and move the manager into it, which saves some duplication.
In a WCF service project, I have created a simple wrapper for MEF CompositionContainer to simplify its instantiation :
internal class CompositionProxy
{
private static Lazy<CompositionContainer> m_lazyCC;
static CompositionProxy()
{
m_lazyCC = new Lazy<CompositionContainer>(() =>
{
var batch = new CompositionBatch();
var dc1 = new DirectoryCatalog(
HttpContext.Current.Server.MapPath("~/bin")
);
return new CompositionContainer(dc1);
}
);
}
public static CompositionContainer DefaultContainer
{
get
{
return m_lazyCC.Value;
}
}
}
The idea is to have one CompositionContainer for the application lifetime, which search for export in the bin directory.
Then, I set up some webservices, that requires to have on imported property :
All of them are built like this :
public class MyService: IMyService
{
public MyService()
{
CompositionProxy.DefaultContainer.SatisfyImportsOnce(this);
}
[Import]
private IContext Context { get; set; }
public void DoTheJob()
{
// Logic goes here
}
}
Elsewhere, I have one class that match this export :
[Export(typeof(IContext))]
public class MyContext
{
public MyContext(){
Log("MyContext created");
}
}
In the constructor, I ask the composition container to populate the IContext Context property.
This seems to work, in my service, I can see the Context property is correctly populated.
However, I'm experiencing memory leaks, and my tracing show me the MyContext class is instantiated only once.
Can you clarify if I'm misusing the composition framework ?
I supposed it's a good idea to have one composition container for the application lifetime, was I wrong ?
the multiple calls to SatisfyImportsOnce seems to populate the target with the same unique instance. Is it true ? If true, how can I simply change my code to have a new instance each time the method is called ?
Any suggestion to improve my code ?
I supposed it's a good idea to have one composition container for the application lifetime
Yes, you are supposed to create one container for the application lifetime.
the multiple calls to SatisfyImportsOnce seems to populate the target with the same unique instance. Is it true ? If true, how can I simply change my code to have a new instance each time the method is called ?
You need [Import(RequiredCreationPolicy=CreationPolicy.NonShared)].
Any suggestion to improve my code ?
If possible, do not expose the container as a global and litter your code with calls to it. That's the Service Locator pattern, which has some disadvantages when compared to Dependency Injection. Instead of your service trying to compose itself, just declare what it needs:
[Export(typeof(IMyService))]
public class MyService: IMyService
{
private readonly IContext context;
public MyService(
[Import(typeof(IContext),
RequiredCreationPolicy=CreationPolicy.NonShared)]
IContext context)
{
if (context == null)
throw new ArgumentNullException("context");
this.context = context;
}
public void DoTheJob()
{
// Logic goes here
}
}
In a WCF service, I think you should only need to call the container in your ServiceHostFactory implementation. I'm not really familiar with WCF though.