UnitOfWork类的结构图和生命周期

时间:2012-12-30 08:48:40

标签: c# dependency-injection ef-code-first structuremap

我使用结构图库和以下代码在WinForm App中配置DI:

 private static void InitializeStructureMap()
        {
            ObjectFactory.Initialize(x =>
            {
                x.For<IUnitOfWork>().HybridHttpOrThreadLocalScoped().Use
                    <CouponContext>();


                x.For<ICouponService>().Use<EFCouponService>();
                x.For<IUserService>().Use<EFUserService>();
            });
        }

我还使用以下代码以表格形式获取类的GetInstance:

private IUnitOfWork uow;
private IUserService userService;

public LoginForm()
{
    InitializeComponent();

    uow = ObjectFactory.GetInstance<IUnitOfWork>();
    userService = ObjectFactory.GetInstance<IUserService>();
}

我的应用程序中UnitOfWork的生命周期如何?

1 个答案:

答案 0 :(得分:4)

默认情况下,它是每个请求,但您可以配置它

x.For<IUnitOfWork>()
 .LifecycleIs(Lifecycles.GetLifecycle(InstanceScope.Singleton))

来自文档:

PerRequest - The default operation.  A new instance will be created for each request.
Singleton - A single instance will be shared across all requests
ThreadLocal - A single instance will be created for each requesting thread.  Caches the instances with ThreadLocalStorage.
HttpContext - A single instance will be created for each HttpContext.  Caches the instances in the HttpContext.Items collection.
HttpSession - A single instance will be created for each HttpSession.  Caches the instances in the HttpContext.Session collection.  Use with caution.
Hybrid - Uses HttpContext storage if it exists, otherwise uses ThreadLocal storage.