我使用结构映射库和以下代码在 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>();
}
我的应用程序中 UnitOfWork 的生命周期如何?
最佳答案
默认情况下按请求进行,但您可以对其进行配置
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.
关于c# - UnitOfWork类的结构图及生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14089476/