Like that? really?

By on (tags: ASP.NET, dependency injection, categories: tools, web)

So I found this. Please don’t do that. Do something better, it’s easy and less complicated. I’ll show you how.

I doubt that OWIN components have been designed to be used as a DI container and in this post – they certainly seem to be used that way, unless I’m not seeing something.

The idea behind the article IS GOOD. One manager per request – good, one DbContext per request – also good, but why use the OWIN context as a DI container when you can use a … DI container, you’re using one anyway, right?

Most of them (and certainly all of the ones that are worth a while) have asp.net integration (either MVC of WebForms – you name it, they have it) and they also have a possibility to define lifetime scopes like… instance per http request.

So instead of going through all the shenanigans from the article, just use the DI container functionality.

In Autofac it’s more or less like this:

   1: ...
   2: var builder = new ContainerBuilder();
   3: builder.RegisterAssemblyTypes(typeof(IAppContext).Assembly).InstancePerHttpRequest()
   4: ...

and then just inject it into the component that you want to use.

There is one scenario where this may not be the best approach – if they (at some point in time) decide to make the OWIN contexts’ lifetime shorter/longer than the request lifetime, but if they do, I bet that we’ll quickly see a “.InstancePerOwinContext()” extension method in the DI library.

Cheers