Autofac (MVC Example)
Uses an IOC (Inversion of control) container, its simple to setup in an MVC application.
Install Autofac 5.2.0 and Autofac.Extensions.DependencyInjection 6.0.0
Startup.cs
The install should add ConfigureContainer to your Startup.cs, you dont need to build the container, you only nee to register things in it.
1 | public void ConfigureContainer(ContainerBuilder builder) |
Modules
Modules are a cool way to group things in a cohesive manner.
1 | using System.Linq; |
Register things using the builder
You can then use the power of reflection in the DataModule class above to resolve things from a repository, this is cool as it will resolve things like ICoolRepository to CoolRepository because they have the string Repository in their names.
Its pretty common to do this for a Factory too.
1 | builder.RegisterAssemblyTypes(System.Reflection.Assembly.GetAssembly(typeof(SomeBaseClass))) |
You can also look to the namespace when using reflection:
1 | builder.RegisterAssemblyTypes(System.Reflection.Assembly.GetAssembly(typeof(SomeBaseClass))) |
Else if its a once off helper/magic just resolve directly
1 | builder.RegisterInstance(new FooHelper()).As<IFooHelper>().SingleInstance(); |
SingleInstance
Called in the fluent api examples above with .SingleInstance();, remember not have any state in anything that expects to exist as a singleton.
Configure the component so that every dependent component or call to Resolve()
Autofac (Webforms Example)
Uses an IOC (Inversion of control) container. This was useful in a legacy Web Forms application (Autofac, Version=4.8.1.0) however it would have worked just as well in the MVC application I used Unity in.
install Autofac 4.9.1 and Autofac.Web 4.0.0
Update web.config to include this below system.webServer
1 | <modules> |
Add Global.asax if it doesn’t already exist, implement IContainerProviderAccessor
1 | public class Global : System.Web.HttpApplication, IContainerProviderAccessor |
Add some crap
1 | // Provider that holds the application container. |
In your page code behind
1 | namespace MyNameSpace |
Contextual Binding (Keyed Services)
This is the same as Ninjects Contextual Binding but uses .Keyed
Create an enum, for reasons :)
1 | public enum LaunchDarklyProjectEnum |
IoC Module example:
1 | var sdkKeyProjectOne = "sdk-0000000000000000"; |
Resolve with KeyFilter
1 | public class LdFeatureRepository { |