2

我使用结构映射库和以下代码在 WinForm 应用程序中配置 DI:

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


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

我也使用以下代码以一种形式获取类的实例:

private IUnitOfWork uow;
private IUserService userService;

public LoginForm()
{
    InitializeComponent();

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

我的 App 中 UnitOfWork 的生命周期如何?

4

1 回答 1

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.
于 2012-12-30T09:04:35.373 回答