ASP.NET MVC 使用 DI Framework – Autofac

Step01. 安裝 Autofac

Step02. 安裝 Autofac.Mvc5

Step03. 在 App_Start 加入 AutofacConfig.cs

public class AutofacConfig
{
    public static void Bootstrapper()
    {
        var builder = new ContainerBuilder();

        builder.RegisterControllers(Assembly.GetExecutingAssembly());

        builder.RegisterType<TimidoColorDB>()
        .As<ITimidoColorDB>()
        .InstancePerRequest();

        var services = Assembly.Load("TimidoColor.Services");
        builder.RegisterAssemblyTypes(services).AsImplementedInterfaces();

        var helper = Assembly.Load("TimidoColor.Core");
        builder.RegisterAssemblyTypes(helper).AsImplementedInterfaces();

        builder.RegisterFilterProvider();

        IContainer container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    }
}

Step04. Global.asax 加入 AutofacConfig.Bootstrapper();

 

protected void Application_Start()
{
    AutofacConfig.Bootstrapper();

    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}