autofac / Autofac.Owin

OWIN integration for Autofac
MIT License
23 stars 15 forks source link

Put the registration into middlewares #20

Closed kirinboy closed 4 years ago

kirinboy commented 4 years ago

Basically, I can build the container in the Startup.Configuration method and then add the Autofac middleware into the IAppBuilder.

public void Configuration(IAppBuilder application)
{
        var container = BuildContainer();
        app.UseAutofacMiddleware(container);
}

I can also put the registrations into custom middlewares and register different dependencies in different middlewares based on some arguments. For example:

public class HttpClientRegistrationMiddleware : OwinMiddleware
{
    private HttpClientRegistrationOptions options;

    public HttpClientRegistrationMiddleware(OwinMiddleware next, HttpClientRegistrationOptions options) : base(next)
    {
        this.options = options;
    }

    public override async Task Invoke(IOwinContext context)
    {
        if (context.GetAutofacLifetimeScope() != null)
        {
            await Next.Invoke(context);
        }
        else
        {
            var builder = context.Get<ContainerBuilder>(nameof(ContainerBuilder));
            builder.Register(c => options.Handler == null ? new HttpClient() : new HttpClient(options.Handler)).SingleInstance();
            await Next.Invoke(context);
        }        
    }
}

Is it a good practice? Are there any pitfalls about it? Thank you.

tillig commented 4 years ago

It appears you've already posted this to Stack Overflow and we do monitor there already. No need to double post. Thanks!