Search code examples
c#idisposablesimple-injector

How to register a disposable Concrete type in Simple Injector container


I found the following code at Simple Injector Website

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));
}

I want to register a concrete implementation (one that does not implement any particular interface) that is Disposable for the transient scope. What changes do I need to make to the code above


Solution

  • In case you want to register a concrete disposable type, typically the simplest (and best) thing to do is to register it as Scoped:

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

    In case you really need that instance to be transient (unlikely), you will have to do the following.

    It's just a matter of using the CreateRegistration<TConcrete> overload:

    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));
    }