c# - 使用工厂时覆盖 AutoFac 范围配置

标签 c# dependency-injection autofac

如何配置 AutoFac,以便每次访问工厂时都能获得一个新的 Context 实例。 Content 组件设置为 InstancePerLifetimeScope(),这非常适合我 99% 的使用,但现在我需要对 Context< 的使用方式进行一些额外的控制 组件是有作用域的。

class Program
{
    static void Main(string[] args)
    {
        var builder = new ContainerBuilder();

        builder.RegisterType<Box>();
        builder.RegisterType<DbContext>().InstancePerLifetimeScope();

        var container = builder.Build();

        using (var scope = container.BeginLifetimeScope())
        {
            var x = scope.Resolve<Box>();
        }

        Console.ReadKey();
    }
}

class Box
{
    public Box(DbContext.Factory factory)
    {
        factory();
        factory(); // Want this to generate a NEW instance

        Console.WriteLine("Box: {0}", GetHashCode());
    }
}

class DbContext
{
    public delegate DbContext Factory();

    public DbContext()
    {
        Console.WriteLine("Context: {0}", GetHashCode());
    }
}

显然,这是一段相当简化的代码片段。我试图解决的问题是,我有大量数据进入服务,并且我正在尝试批量保存到数据库。因此,如果 Box 可以根据需要创建新的 UOW,并及时释放它们以供处置,那么我就得到了一个很好的干净解决方案。

谢谢!

最佳答案

您可以使用Func<Owned<>>它的工作原理就像一个小ILifetimeScope :

public Box(Func<Owned<DbContext>> factory)
{
    using (Owned<DbContext> ownedDbContext = factory())
    {
        // instance1
    }
    using (Owned<DbContext> ownedDbContext = factory())
    {
        // instance2 
    }
}

您可以在 Autofac 文档中找到更多详细信息:Owned Instances

另一个解决方案是注入(inject) ILifetimeScope然后创建一个子生命周期范围:

public Box(ILifetimeScope scope)
{
    using (ILifetimeScope subScope = scope.BeginLifetimeScope())
    {
        DbContext dbContext = subScope.Resolve<DbContext>();
    }
}

public Box(ILifetimeScope scope)
{
    ILifetimeScope subScope = scope.BeginLifetimeScope();
    scope.Disposer.AddInstanceForDisposal(subScope);
    DbContext dbContext = subScope.Resolve<DbContext>(); 
    // no need to dispose subScope, 
    // subScope (and dbContext) will be disposed at the same time as scope
}

关于c# - 使用工厂时覆盖 AutoFac 范围配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28989777/

相关文章:

ios - 如何在 Storyboard管理的 UIViewControllers 中依赖注入(inject)?

c# - 如何设置 ASP.Net 3.0 Core Web API 项目来使用 AutoFac 和 NLog?

c# - 如何测量和监控单个组件的 Autofac 解析时间

c# - ScrollViewer 本身的垂直偏移量与 PropertyChangedEventArgs 的垂直偏移量有什么区别

c# - 在运行时确定 .NET Standard DLL 中的框架

c# - 为 Json 对象生成 C# 类的优缺点

autofac - 替换 Autofac 中的注册

c# - Excel Interop 工作表列表有额外工作表,UsedRange 没有数据

dependency-injection - 使用 Ninject、MVC 3 和使用服务定位器模式的依赖注入(inject)

c# - 使用缓存依赖项对 MVC 操作方法进行单元测试?