Structuremap Disposing of DataContext object

回眸只為那壹抹淺笑 提交于 2019-12-19 07:10:11

问题


I wanted to be sure if structuremap will dispose my DataContext after per request ends.

Here is my setup

ForRequestedType<MyDataContext>().TheDefault.Is.OfConcreteType<MyDataContext>();
SelectConstructor<MyDataContext>(() => new MyDataContext());

Will structuremap auto dispose my datacontext or do i need to call Dispose manually??


回答1:


No it will not Dispose it automatically, unless you use nested containers and Dispose the container holding the context instance. It's up to the creator of the context to Dispose it. The creator would usually be the part of your code calling ObjectContext.GetInstance<MyDataContext> or the root method that makes StructureMap inject a DataContext into one of your objects.

A common practice is to create a context per HttpRequest and dispose the context at the end of the request.




回答2:


That's what I do:

    For<IUnitOfWork>()
        .HybridHttpOrThreadLocalScoped()
        .Use<BpReminders.Data.NH.UnitOfWork>();

    For<ISession>()
        .HybridHttpOrThreadLocalScoped()
        .Use(o => ((BpReminders.Data.NH.UnitOfWork)o.GetInstance<IUnitOfWork>()).CurrentSession);

and ...

protected void Application_EndRequest(object sender, EventArgs e)
{
    ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
}

HybridHttpOrThreadLocalScoped uses the HttpContext when available.

StructureMap looks after everything, then. Just remember to implement IDisposable in your classes.



来源:https://stackoverflow.com/questions/5015354/structuremap-disposing-of-datacontext-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!