In my application I am making use of Spring.Net for IoC. The service objects are called from the ASP.Net files to perform CRUD operations using these service object. For example, I have CustomerService to do all CRUD operations on Customer table. I use entity framework and the entities are injected .. my question is where do I call the dispose method?
As far as I understood from the API documentations, unless I call Dispose() there is no guaranty it will be garbage collected! So where and how do I do it?
Example Service Class:
public class CustomerService
{
public ecommEntities entities = {get; set;}
public bool AddCustomer(Customer customer)
{
try
{
entities.AddToCustomer(customer);
entities.SaveChanges();
return true;
}
catch (Exception e)
{
log.Error("Error occured during creation of new customer: " + e.Message + e.StackTrace);
return false;
}
}
public bool UpdateCustomer(Customer customer)
{
entities.SaveChanges();
return true;
}
public bool DeleteCustomer(Customer customer)
.
.
.
And I just create an object of CustomerService at the ASP partial class and call the necessary methods.
Thanks in advance for the best practice and ideas..
Regards,
Abdel Raoof
I have HttpModule in my application, which takes care of creating and disposing of context:
public class MyEntitiesHttpModule : IHttpModule
{
public void Init(HttpApplication application)
{
application.BeginRequest += ApplicationBeginRequest;
application.EndRequest += ApplicationEndRequest;
}
private void ApplicationEndRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Items[#"MyEntities"] != null)
((MyEntities)HttpContext.Current.Items[#"MyEntities"]).Dispose();
}
private static void ApplicationBeginRequest(Object source, EventArgs e)
{
//TextWriter logFile = File.CreateText(HttpContext.Current.Server.MapPath("~/sqllogfile.txt"));
var context = new MyEntities();
//context.Log = logFile;
HttpContext.Current.Items[#"MyEntities"] = context;
}
}
It creates it at the beginning of request and disposes at the end. Context is taken from HttpContext.Current.Items by Ninject and injected into my service object. I don't know how exactly it works with Spring.Net and what is your approach to creating ObjectContext, but I hope this answer will help. If Sprint.Net supports per request lifetime and doesn't need any modules, it propably takes care of disposing too. In other case, you can do it like here.
#LukLed is generally correct (+1) that the HTTP request is the correct scope. However, I very much doubt explicit code is required to call Dispose() with either NInject or Spring.Net as both of these should already be disposing instances they manage. HttpContext.Current is as good a place to store the reference as anything.
However, you (#Abdel) are wrong to say:
As far as I understood from the API documentations, unless I call Dispose() there is no guaranty it will be garbage collected!
This is just not right. Dispose() makes the collection somewhat more optimal and provides for deterministic release of unmanaged resources (e.g., your DB connection). But everything will eventually be collected, with or without calling Dispose().
Related
I am using Unity and Entity Framework in a Web API 2 application. I register types with the HierarchicalLifetimeManager.
var container = new UnityContainer();
container.RegisterType<IService, Service>(new HierarchicalLifetimeManager());
Do I need to wrap all my dbContext calls in a using statement like this? Is this needed? I thought Unity will dispose the context for me.
using (var client = new dbContext())
{
var result = client.Customers.toList();
}
Or can I just use dbContext without the using statement?
Do I need to wrap all my dbContext calls in a using statement like
this?
I would say that it depends on how you use your context. Take this example:
public class Service : IService, IDisposable
{
private DbContext _context;
public Service(DbContext context)
{
_context = context;
}
public object Get(int id)
{
return _context.Customers.Find(id);
}
public object Update(object obj)
{
// Code for updating
}
public void Dispose()
{
_context.Dispose();
}
}
If you register Service with HierarchicalLifetimeManager the context will practially never be disposed, since nothing will dispose the service and thus never dispose the context. However, the example above should work fine with TransientLifetimeManager.
From MSDN:
HierarchicalLifetimeManager. For this lifetime manager, as for the
ContainerControlledLifetimeManager, Unity returns the same instance of
the registered type or object each time you call the Resolve or
ResolveAll method or when the dependency mechanism injects instances
into other classes.
If you instead dispose it in each method, then it will be correctly disposed regardless of what lifetimemanager you use. Also, the consumer of IService doesn't need to care about disposing IService.
public class Service : IService
{
public object Get(int id)
{
using (var context = new DbContext())
{
return context.Customers.Find(id);
}
}
public object Update(object obj)
{
// Code for updating
}
}
Also, consider what happens if your Service was Transient, and is injected in a manager that is ContainerController. Since the manager never is disposed, neither is the service. The manager will keep the same instance of the service throughout the lifetime of the container. Therefore I personally suggest that you keep the disposing of the context outside of the containers control. It can work very well with the help of lifetimemanagers if you make sure that you have a chain of disposings. There are several posts here and on codereview that show examples of UoW with Unity to dispose the context.
I am running into an issue where I can't figure out how to properly dispose of my object context I am creating every time I instantiate a new object.
public class OrderBLL{
var _iOrderLineDal;
public OrderBLL(){
_iOderLineDal = new OrderLineDal(new entityOBject(dbconnectionstring);
}
public OrderBLL(iOrderLineDal mockOrderLineDal){
_iOrderLineDal = mockOrderLineDal;
}
}
So the problem is, that every 30 seconds my service creates a new instance of the OrderBLL and then runs a method to see if there are any new orders in the Data base.
So every 30 seconds I create a new entityObject that is not being disposed of. the old implementation of the code was written using the using statement.
public bool HasNewOrders(){
using(var entityObject = new entityObject(dbconnectionString)){
var newOrders = entityObject.GetNewOrders();
}
//some logic
}
The problem with using this using statement is I cannot mock out the entityObject and easily write unit tests on any methods inside this OrderBLL class.
I tried disposing of it with a dispose method inside the OrderLineDal and once i got the data called dispose. That worked well the first iteration but the following iterations, the next 30 seconds, it would say that the entityObject was disposed of and cannot be used. (doesn't make sense to me, since I am creating a new one every time?)
Is there a way I can implement this repository pattern and still dispose of all the new entityObjects so I can mock the DAL out for unit testing?
I am working with EF 4. and it was not set up Code First, so I do not have POCO.
Ideally you would want to create your context outside of your OrderBLL (search google for Repository pattern).
public class OrderRepository : IOrderRepository, IDisposable
{
private readonly IOrderDBContext _dbContext;
// poor mans dependency injection
public OrderRepository() : this(new OrderDbContext("YourConnectionString")
{}
public OrderRepository(IOrderDBContext dbContext)
{
if (dbContext == null) throw new ArgumentNullException("dbContext");
_dbContext = dbContext;
}
public bool GetNewOrders(){
return _dbContext.Orders.Where(o => o.IsNew==true);
}
public void Dispose()
{
if (_dbContext != null) _dbContext.dispose();
}
}
public class OrderBLL : IOrderBLL
{
private readonly IOrderRepository _repository;
public OrderRepository(IOrderRepository repository)
{
if (repository == null) throw new ArgumentNullException("dbContext");
_repository = repository;
}
public bool HasNewOrders(){
var newOrders = _repository.GetNewOrders();
if (newOrders==null) return false;
return newOrders.Count() > 0;
}
}
[Test]
public void HasNewOrders_GivenNoNNewOrdersRetunedFromRepo_ReturnsFalse()
{
// test using nunit and nsubstitute
// Arrange
var repository = Substitue.For<IOrderRepository>();
var emptyOrderList = new List<Order>();
repository.GetNewOrders().Returns();
var orderBLL = new OrderBLL(repository);
// Act
var result = orderBLL.HasNewOrders();
// Assert
Assert.Equals(false, result);
}
Now you can inject your context into this class and easily test your business logic. Eventually you will need to create your dbContext and should also always expose this. I would suggest having a look at a DI container like Castle Windsor to manage the life of your objects, although in a service you may just want to manually create and dispose your context as close to the code entry point as possible (e.g. in the main method)
Note: I am not planning to use the Entity Framework as it does NOT support async queries.
I am unable to figure out which approach would be better for the following scenario with Dependency Injection and SQL Connection Pooling.
SQL Server Connection Pooling (ADO.NET) MSDN article recommends to use using (sqlConn) since I don't take a hit on connection.Open() and connection.Close() with Connection Pooling enabled.
Technique 1:
Inject a SqlConnection dependency into my CustomerRepository class.
Use an instance per HTTP Request for the SqlConnection.
Call connection.Open() before it is injected into the CustomerRepository class.
Technique 2:
Only inject the Connection String into my CustomerRepository class.
Initialize using (SqlConnection) blocks in each of my CRUD methods?
Additional Things to Consider
I will be using async calls with my SqlCommand.BeginExecuteReader() for some SQL queries that takes about 2-4 seconds to execute.
In some special scenarios, I need to run 2-or-more parallel SQL query calls as well.
Please also keep in mind how the two techniques affect the coding style for IDisposable and using (connection) stuff.
Questions
Are there any differences between the two approaches given the fact that Connection Pooling is enabled?
Which technique should I use and why?
Code Sample for Technique 1:
// ------------------------------------------------------------
// Autofac Dependency Injection setup
// ------------------------------------------------------------
ContainerBuilder builder = new ContainerBuilder();
builder.Register(
c => {
var conn = new SqlConnection( "connectionString" );
conn.Open(); // open the connection ahead of time before injecting it into my CustomerRepository
return conn;
})
.Named("myNamedConnection", typeof(SqlConnection))
.InstancePerHttpRequest();
builder.Register(
c => {
new CustomerRepository(c.ResolveNamed<SqlConnection>("myNamedConnection")))
})
.As<ICustomerRepository>();
// ------------------------------------------------------------
// CustomerRepository
// ------------------------------------------------------------
public class CustomerRepository : ICustomerRepository, IDisposable
{
private SqlConnection conn;
private bool disposed;
public CustomerRepository(SqlConnection connection)
{
conn = connection;
disposed = false;
}
public Customer GetById(int id)
{
using (var cmd = conn.CreateCommand())
{
// code to retrieve Customer by id
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
if (conn != null)
{
conn.Dispose();
conn = null;
}
}
disposed = true;
}
}
}
Code Sample for Technique 2:
// ------------------------------------------------------------
// CustomerRepository
// ------------------------------------------------------------
public class CustomerRepository : ICustomerRepository
{
private readonly string strConn;
public CustomerRepository(string strConnection) // strConnection has Connection Pooling enabled
{
strConn = strConnection;
}
public Customer GetById(int id)
{
using (var conn = new SqlConnection(this.strConn))
{
using (var cmd = conn.CreateCommand())
{
// code to retrieve Customer by id
}
}
}
}
Thanks in advance for any thoughtful inputs :-)
Don't go for technique 1. Leaving the connection open for the complete request is not adviced: it should be closed as soon as possible, so don't leave it open for the complete request.
Don't go for technique 2. Injecting a connection string in each and every repository is cumbersome and if you are doing that, it seems to me that you are missing an abstraction, in your code. You probably don't want every repository create a new SqlConnection by itself.
You might be better of by injecting an IDatabase abstraction of some sort into your repositories. You can inject the connection string in your IDatabase implementation. This abstraction can have a BeginExecuteReader method or perhaps even some higher level abstraction.
I have a MVC 2.0 application using Ninject.Web.Mvc2 and a repository pattern (built over an entity framework model ). I am trying to create a new ObjectContext that will only live for the duration of the request. I am attempting to accomplish this in the following manner:
protected override IKernel CreateKernel(){
var kernel = new StandardKernel();
kernel.Load(Assembly.GetExecutingAssembly());
return kernel;
}
protected override void OnApplicationStarted()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
I then ran out of ideas for keeping this generic enough so I set to work in the BeginRequest:
protected void Application_BeginRequest()
{
string EntityConnectionString = ConfigurationManager.ConnectionStrings["Entities"].ConnectionString;
HttpContext.Current.Items.Add(_PerRequestContextObjectKey, new EntityFrameworkContextWrapper(EntityConnectionString));
this.Kernel.Bind<IUserRepository>().To<UserRepository>().WithConstructorArgument("ContextWrapper", HttpContext.Current.Items[_PerRequestContextObjectKey]);
}
The Wrapper class is just a generic object for including anything I want to kill at the end of request. In this specific case, I use it to create my new ObjectContext and also implement IDisposable so I can do the following:
protected void Application_EndRequest()
{
foreach (var Item in HttpContext.Current.Items)
{
if (Item.GetType() == typeof(IPerRequestLifetimeObjectWrapper))
{
(Item as IPerRequestLifetimeObjectWrapper).Dispose();
}
}
}
I'm sure it's not the prettiest way of doing this, but at this point I'm trying to get moving since I've spent so much time "learning" all this stuff.
My Controller is then injected like so:
public class AdminUserController : Controller
{
// Mark for Ninject
[Inject] public IUserRepository _userRepo { get; set; }
public ViewResult Index( )
{
return View(_userRepo.Get);
}
public ViewResult Edit(Guid UserUID)
{
return View(_userRepo.GetById(UserUID));
}
}
and my Repository gets injected as well:
[Inject]
public UserRepository(EntityFrameworkContextWrapper ContextWrapper )
// Mark for Ninject Dependency Injection
// Must receive Wrapper that contains active ObjectContext
{
_db = ContextWrapper.Entities; //Not actually named this, just easier for typing right now
}
When my Controller calls the Get method inside my UserRepository object the first time it works great. If I hit refresh ( or I'm guessing postback as well ), _db is Null. When I try to step through the debugger, I find that the Controller Index( ) method is being called before a Application_BeginRequest() is called. I thought I had an understanding of the "pipeline" ( I'm used to calling things page lifecycle from WebForms ), but now I'm a bit lost. Can someone elaborate on where my brain has some wires crossed? Like I said, this probably isn't the prettiest method, but I've only had about a week and a half to learn MVC, DI with Ninject, Repository, and Entity Framework so please don't feel like you're talking down to me if it seems like I broke something very basic.
Why don't you simply use InRequestScope? What you do is adding a new binding for each request. This will lead to severe problems.
See https://github.com/ninject/ninject.web.mvc/wiki/Unit-of-work-pattern-with-nhibernate
It's NHilbernate but you can do the same with EntityFramework
I'm using StructureMap to resolve references to my repository class. My repository interface implements IDisposable, e.g.
public interface IMyRepository : IDisposable
{
SomeClass GetById(int id);
}
An implementation of the interface using Entity Framework:
public MyRepository : IMyRepository
{
private MyDbContext _dbContext;
public MyDbContext()
{
_dbContext = new MyDbContext();
}
public SomeClass GetById(int id)
{
var query = from x in _dbContext
where x.Id = id
select x;
return x.FirstOrDefault();
}
public void Dispose()
{
_dbContext.Dispose();
}
}
Anyway as mentioned I'm using StructureMap to resolve IMyRepository. So when, where and how should I call my dispose method?
WARNING: please note that my views have changed, and you should consider the following advise outdated. Please see this answer for an updated view: https://stackoverflow.com/a/30287923/264697
While DI frameworks can manage lifetime of objects for you and some could even dispose objects for you after you're done using with them, it makes object disposal just too implicit. The IDisposable interface is created because there was the need of deterministic clean-up of resources. Therefore, in the context of DI, I personally like to make this clean-up very explicit. When you make it explicit, you've got basically two options: 1. Configure the DI to return transient objects and dispose these objects yourself. 2. Configure a factory and instruct the factory to create new instances.
I favor the second approach over the first, because especially when doing Dependency Injection, your code isn't as clean as it could be. Look for instance at this code:
public sealed class Client : IDisposable
{
private readonly IDependency dependency;
public Client(IDependency dependency)
{
this. dependency = dependency;
}
public void Do()
{
this.dependency.DoSomething();
}
public Dispose()
{
this.dependency.Dispose();
}
}
While this code explicitly disposes the dependency, it could raise some eyebrows to readers, because resources should normally only be disposed by the owner of the resource. Apparently, the Client became the owner of the resource, when it was injected.
Because of this, I favor the use of a factory. Look for instance at this example:
public sealed class Client
{
private readonly IDependencyFactory factory;
public Client(IDependencyFactory factory)
{
this.factory = factory;
}
public void Do()
{
using (var dependency = this.factory.CreateNew())
{
dependency.DoSomething();
}
}
}
This example has the exact same behavior as the previous example, but see how the Client class doesn't have to implement IDisposable anymore, because it creates and disposes the resource within the Do method.
Injecting a factory is the most explicit way (the path of least surprise) to do this. That's why I prefer this style. Downside of this is that you often need to define more classes (for your factories), but I personally don't mind.
RPM1984 asked for a more concrete example.
I would not have the repository implement IDisposable, but have a Unit of Work that implements IDisposable, controls/contains repositories and have a factory that knows how to create new unit of works. With that in mind, the above code would look like this:
public sealed class Client
{
private readonly INorthwindUnitOfWorkFactory factory;
public Client(INorthwindUnitOfWorkFactory factory)
{
this.factory = factory;
}
public void Do()
{
using (NorthwindUnitOfWork db =
this.factory.CreateNew())
{
// 'Customers' is a repository.
var customer = db.Customers.GetById(1);
customer.Name = ".NET Junkie";
db.SubmitChanges();
}
}
}
In the design I use, and have described here, I use a concrete NorthwindUnitOfWork class that wraps an IDataMapper that is the gateway to the underlying LINQ provider (such as LINQ to SQL or Entity Framework). In sumary, the design is as follows:
An INorthwindUnitOfWorkFactory is injected in a client.
The particular implementation of that factory creates a concrete NorthwindUnitOfWork class and injects a O/RM specific IDataMapper class into it.
The NorthwindUnitOfWork is in fact a type-safe wrapper around the IDataMapper and the NorthwindUnitOfWork requests the IDataMapper for repositories and forwards requests to submit changes and dispose to the mapper.
The IDataMapper returns Repository<T> classes and a repository implements IQueryable<T> to allow the client to use LINQ over the repository.
The specific implementation of the IDataMapper holds a reference to the O/RM specific unit of work (for instance EF's ObjectContext). For that reason the IDataMapper must implement IDisposable.
This results in the following design:
public interface INorthwindUnitOfWorkFactory
{
NorthwindUnitOfWork CreateNew();
}
public interface IDataMapper : IDisposable
{
Repository<T> GetRepository<T>() where T : class;
void Save();
}
public abstract class Repository<T> : IQueryable<T>
where T : class
{
private readonly IQueryable<T> query;
protected Repository(IQueryable<T> query)
{
this.query = query;
}
public abstract void InsertOnSubmit(T entity);
public abstract void DeleteOnSubmit(T entity);
// IQueryable<T> members omitted.
}
The NorthwindUnitOfWork is a concrete class that contains properties to specific repositories, such as Customers, Orders, etc:
public sealed class NorthwindUnitOfWork : IDisposable
{
private readonly IDataMapper mapper;
public NorthwindUnitOfWork(IDataMapper mapper)
{
this.mapper = mapper;
}
// Repository properties here:
public Repository<Customer> Customers
{
get { return this.mapper.GetRepository<Customer>(); }
}
public void Dispose()
{
this.mapper.Dispose();
}
}
What's left is an concrete implementation of the INorthwindUnitOfWorkFactory and a concrete implementation of the IDataMapper. Here's one for Entity Framework:
public class EntityFrameworkNorthwindUnitOfWorkFactory
: INorthwindUnitOfWorkFactory
{
public NorthwindUnitOfWork CreateNew()
{
var db = new ObjectContext("name=NorthwindEntities");
db.DefaultContainerName = "NorthwindEntities";
var mapper = new EntityFrameworkDataMapper(db);
return new NorthwindUnitOfWork(mapper);
}
}
And the EntityFrameworkDataMapper:
public sealed class EntityFrameworkDataMapper : IDataMapper
{
private readonly ObjectContext context;
public EntityFrameworkDataMapper(ObjectContext context)
{
this.context = context;
}
public void Save()
{
this.context.SaveChanges();
}
public void Dispose()
{
this.context.Dispose();
}
public Repository<T> GetRepository<T>() where T : class
{
string setName = this.GetEntitySetName<T>();
var query = this.context.CreateQuery<T>(setName);
return new EntityRepository<T>(query, setName);
}
private string GetEntitySetName<T>()
{
EntityContainer container =
this.context.MetadataWorkspace.GetEntityContainer(
this.context.DefaultContainerName, DataSpace.CSpace);
return (
from item in container.BaseEntitySets
where item.ElementType.Name == typeof(T).Name
select item.Name).First();
}
private sealed class EntityRepository<T>
: Repository<T> where T : class
{
private readonly ObjectQuery<T> query;
private readonly string entitySetName;
public EntityRepository(ObjectQuery<T> query,
string entitySetName) : base(query)
{
this.query = query;
this.entitySetName = entitySetName;
}
public override void InsertOnSubmit(T entity)
{
this.query.Context.AddObject(entitySetName, entity);
}
public override void DeleteOnSubmit(T entity)
{
this.query.Context.DeleteObject(entity);
}
}
}
You can find more information about this model here.
UPDATE December 2012
This an an update written two years after my original answer. The last two years much has changed in the way I try to design the systems I'm working on. Although it has suited me in the past, I don't like to use the factory approach anymore when dealing with the Unit of Work pattern. Instead I simply inject a Unit of Work instance into consumers directly. Whether this design is feasibly for you however, depends a lot on the way your system is designed. If you want to read more about this, please take a look at this newer Stackoverflow answer of mine: One DbContext per web request…why?
If you want to get it right, i'd advise on a couple of changes:
1 - Don't have private instances of the data context in the repository. If your working with multiple repositories then you'll end up with multiple contexts.
2 - To solve the above - wrap the context in a Unit of Work. Pass the unit of work to the Repositories via the ctor: public MyRepository(IUnitOfWork uow)
3 - Make the Unit of Work implement IDisposable. The Unit of Work should be "newed up" when a request begins, and therefore should be disposed when the request finishes. The Repository should not implement IDisposable, as it is not directly working with resources - it is simply mitigating them. The DataContext / Unit of Work should implement IDispoable.
4 - Assuming you are using a web application, you do not need to explicitly call dispose - i repeat, you do not need to explicitly call your dispose method. StructureMap has a method called HttpContextBuildPolicy.DisposeAndClearAll();. What this does is invoke the "Dispose" method on any HTTP-scoped objects that implement IDisposable. Stick this call in Application_EndRequest (Global.asax). Also - i believe there is an updated method, called ReleaseAllHttpScopedObjects or something - can't remember the name.
Instead of adding Dispose to IMyRepository, you could declare IMyRepository like this:
public interface IMyRepository: IDisposable
{
SomeClass GetById(int id);
}
This way, you ensure all repository will call Dispose sometimes, and you can use the C# "using" pattern on a Repository object:
using (IMyRepository rep = GetMyRepository(...))
{
... do some work with rep
}