c# - UnitOfWork类的结构图及生命周期

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

我使用结构映射库和以下代码在 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/

相关文章:

c# - asp.net c#DetailView如何设置列宽

c# - Nodejs 验证来自 .net 的 jwt token 失败

c# - 我应该使用什么 ORM for .net?

c# - 如何使用依赖注入(inject)完成可变对象重构?

c# - 温莎城堡 : Force resolver to use specified constructor

sql-server-2008 - Entity Framework 代码优先权限/数据库创建问题

c# - EF Code First,从多对多关系中公开链接表/对象?

c# - 在Docker内部将npm安装后没有node_modules文件夹

angular - 为什么 Angular CLI 不会自动在提供者数组中添加服务?

entity-framework - 如何使用 Entity Framework 代码优先方法创建索引 View