June 22, 2021

Using AutoFac for Dependency Injection

Create the Autofac builder:
    // Step 1. Create the builder with which components/services are registered.
    var builder = new ContainerBuilder();

    // Step 2. 
    RegisterTypesWithAutoFac(builder); // Register your types here (see below)

    // Step 3.
    // Build the container to finalize registrations
    // and prepare for object resolution.
    var container = builder.Build();

    // Step 4.
    // Now you can resolve services using Autofac.
    using(var scope = container.BeginLifetimeScope())
    {
      var reader = scope.Resolve<IConfigReader>();
    }
However in MVC 5 replace Step 4 with this:
    var mvcResolver = new AutofacDependencyResolver(container);
    DependencyResolver.SetResolver(mvcResolver);

Registering Types
Here are a few key examples of registering types.
Case 1: Instance on Request:

builder.RegisterType<SystemDistanceCalculator>().
    As<ISystemDistanceCalculator>().
    InstancePerRequest();
Case 2: A singleton instance
builder.RegisterType<SystemIdsCachesManager>().
    As<ISystemIdsCachesManager>().
    SingleInstance();
Case 3: Initializing Parameters Example
builder.RegisterType<PermitSystemsFactory>().
    As<IPermitSystemsFactory>().
    WithParameter("repositoryPath", EliteDangerousPaths.PermitSystemsJsonlPath).
    SingleInstance();
Case 4: Using a lambda to perform some of the object initialization
builder.Register(c =>
{
    var edSystemsDb = new EdSystemsSqlDb();
    var sqlServerConfig = c.Resolve<ISqlServerConfiguration>();
    edSystemsDb.Initialise(sqlServerConfig.ConnectionString);
    return edSystemsDb;
}).
    As<IEdSystemsDb>().
    SingleInstance();

No comments: