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.
Basically, I can build the container in the
Startup.Configuration
method and then add the Autofac middleware into theIAppBuilder
.I can also put the registrations into custom middlewares and register different dependencies in different middlewares based on some arguments. For example:
Is it a good practice? Are there any pitfalls about it? Thank you.