Getting started with Autofac with MVC and Kentico 12

//Initialize builder
var builder = new ContainerBuilder();
            
builder.RegisterSource(new ViewRegistrationSource());
builder.RegisterModule<AutofacWebTypesModule>();
builder.RegisterControllers(typeof(KenticoApplication).Assembly);

// Register repository
builder.RegisterAssemblyTypes(typeof(KenticoApplication).Assembly)
    .Where(m => m.IsClass && !m.IsAbstract && typeof(IRepository).IsAssignableFrom(m))
    .AsImplementedInterfaces()
    .InstancePerRequest();

// Register service
builder.RegisterAssemblyTypes(typeof(KenticoApplication).Assembly)
    .Where(m => m.IsClass && !m.IsAbstract && typeof(IService).IsAssignableFrom(m))
    .AsImplementedInterfaces()
    .InstancePerRequest();

//Register with differetn name then interface
builder.RegisterType<HomeRepository2>().As<IHomeRepository>().InstancePerLifetimeScope();

//Build
DependencyResolver.SetResolver(new AutofacDependencyResolver(builder.Build()));

Call this above method in Application Start.

KenticoApplication is Global.ascx.cs class name who inherits to System.Web.HttpApplication In here

Note: Autofac can resolver all the dependency if the name is same else it will not like if my interface is with name IHomeRepository and implementation is in HomeRepository then it will resolve automatically but it will not resolve HomeRepository2 that will have to register manually.

One thought on “Getting started with Autofac with MVC and Kentico 12”

  1. Ooh really actually i didn’t get any chance to work with autofac.
    can you explain thoroughly exacly when we should use autofac ?
    thanks for share this information.

Leave a Reply

Your email address will not be published. Required fields are marked *