如何在简单注入器容器中注册一次性混凝土类型

本文关键字:注册 一次性 混凝土 类型 简单 注入器 | 更新日期: 2023-09-27 18:11:58

我在Simple Injector网站上找到了以下代码

public static void RegisterDisposableTransient<TService, TImplementation>(
    this Container container)
    where TImplementation : class, IDisposable, TService
    where TService : class
{
    var scoped = Lifestyle.Scoped;
    var reg = Lifestyle.Transient.CreateRegistration<TService, TImplementation>(
        container);
    reg.SuppressDiagnosticWarning(DiagnosticType.DisposableTransientComponent, 
            "suppressed.");
    container.AddRegistration(typeof(TService), reg);
    container.RegisterInitializer<TImplementation>(
        o => scoped.RegisterForDisposal(container, o));
}

我想注册一个具体的实现(一个不实现任何特定接口的实现),它是transient作用域的Disposable。我需要对上面的代码

如何在简单注入器容器中注册一次性混凝土类型

做什么更改?

如果您想要注册一个具体的一次性类型,通常最简单(也是最好)的方法是将其注册为Scoped:

container.Register<MyConcrete>(Lifestyle.Scoped);

如果您确实需要该实例是暂态的(不太可能),则必须执行以下操作。

这只是一个使用CreateRegistration<TConcrete>过载的问题:

public static void RegisterDisposableTransient<TConcrete>(this Container container)
    where TConcrete : class, IDisposable
{
    var scoped = Lifestyle.Scoped;
    var reg = Lifestyle.Transient.CreateRegistration<TConcrete>(container);
    reg.SuppressDiagnosticWarning(DiagnosticType.DisposableTransientComponent, "suppres");
    container.AddRegistration(typeof(TConcrete), reg);
    container.RegisterInitializer<TConcrete>(
        o => scoped.RegisterForDisposal(container, o));
}