Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Put the registration into middlewares #20

Closed
kirinboy opened this issue Jun 3, 2020 · 1 comment
Closed

Put the registration into middlewares #20

kirinboy opened this issue Jun 3, 2020 · 1 comment

Comments

@kirinboy
Copy link

kirinboy commented Jun 3, 2020

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
Copy link
Member

tillig commented Jun 3, 2020

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

@tillig tillig closed this as completed Jun 3, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants