在WebApi中使用Unity解决每个请求的dbcontext

Ota*_*ake 14 c# entity-framework dependency-injection asp.net-web-api

我正在努力使这项工作.我已经安装了Unity和Unity.AspNet.WebApi软件包(v 3.5.1404),并且下面附带了激活码

public static class UnityWebApiActivator
{
    /// <summary>Integrates Unity when the application starts.</summary>
    public static void Start() 
    {
        var container = UnityConfig.GetConfiguredContainer();
        var resolver = new UnityHierarchicalDependencyResolver(container);

        GlobalConfiguration.Configuration.DependencyResolver = resolver;

        // DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
    }

    /// <summary>Disposes the Unity container when the application is shut down.</summary>
    public static void Shutdown()
    {
        var container = UnityConfig.GetConfiguredContainer();
        container.Dispose();
    }
}
Run Code Online (Sandbox Code Playgroud)

我的类型注册看起来像这样:

 public static void RegisterTypes(IUnityContainer container)
        {
            container.RegisterType<IAuditService, AuditService>(
                new PerThreadLifetimeManager(),
                new InjectionConstructor(new SecurityDbContext()));
        }
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经尝试过PerThreadLifetimeManager和TransientLifetimeManager但没有成功.我也得到了Unity.Mvc包并尝试使用msdn建议的PerRequestLifetimeManager,但没有运气.它总是给我相同的dbcontex实例.

我宁愿不包含任何MVC依赖,因为这纯粹是WebApi,但是当我尝试使用Unity.Mvc时,我也结束了一些http运行时错误.

任何人都有一个很好的建议/示例来解决每个请求使用Unity在WebApi中的dbcontext,最好没有任何mvc依赖?

Ota*_*ake 12

我注入db上下文的方式就是这里的问题.Unity会记住创建的实例,并为创建的所有新AuditService实例注入相同的实例.我只需要解决db上下文,如下所示.

container.RegisterType<DbContext, SecurityDbContext>(new PerThreadLifetimeManager());
Run Code Online (Sandbox Code Playgroud)

PerThreadLifetimeManager完成了工作,考虑到每个Web请求将由不同的线程提供服务应该没问题.

  • 在Web应用程序中使用`PerThreadLifetimeManager`是一个[非常非常糟糕的主意](/sf/ask/1021399571/). (11认同)