开发者

How does the Munq IocContainer dispose of registered objects within a lifetime?

I am using Munq as my IoC Container for an ASP.NET MVC3 project using the standard WebActi开发者_如何学Pythonvator that is provided in the NuGet package. Here is a sample registration:

ioc.Register<IUnitOfWork>(i =>
{
    return new UnitOfWork("Data Source=foo");
}).AsRequestSingleton();

How does Munq dispose of the IUnitOfWork object at the end of the request? I don't see any tests in the source on codeplex that would indicate that these are disposed!? [


Munq will not dispose anything. If you need this ability, it would be better to use a different IoC container, such as Autofac.

However, in many cases I doubt the real need for letting the container dispose objects for you. The unit of work is a good example, because your IUnitOfWork would have a Commit() method anyway, which is probably called in the application. The class that calls Commit is most likely responsible for the lifetime of the IUnitOfWork and therefore also for calling commit.

You can solve this by not injecting an IUnitOfWork, but injecting an IUnitOfWorkFactory. The class that needs a unit of work can than do the following:

using (IUnitOfWork unit = this.uowFactory.CreateNew())
{
    // Do some useful stuff.

    unit.Commit();
}

UPDATE Dec 2012:

My opinion about how to register Unit of Work instances has (partially) changed due to new insights and the way I design applications. Instead of injecting a factory, I currently like to inject an IUnitOfWork directly. This means that it would be good to dispose the unit of work when defined scope (such as a web request) ends. As @DaRKoN_ explained, since Munq 3.14 the RequestLifetime disposes instances.

This Stackoverflow question and answer gives a thorough explanation about when and how to inject unit of works directly, instead of injecting factories.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜