AutoFac使用

AutoFac使用方法

设置读取配置文件的方法
AutoFacConfig.cs:
需要安装引用
Autofac3.5.2
Autofac.Configuration3.3.0 =>ConfigurationSettingsReader
Autofac.Owin4.0.0
Autofac.WebApi24.1.0
Autofac.WebApi2.Owin4.0.0
代码

public static class AutoFacConfig
    {
        public static void Register(HttpConfiguration config)
        {
            //AutoFac4.0以上版本才支持此方法
            //var builder = new ContainerBuilder();
            //builder.RegisterModule(new ConfigurationSettingsReader("autofac"));
            //builder.RegisterControllers(Assembly.GetExecutingAssembly());
            //builder.RegisterControllers();
            //var container = builder.Build();
            //DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

           var builder = new ContainerBuilder();

            // 家在所有程序集
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());    // IHttpController in current assembly
            //builder.RegisterModule();                      // IHttpController in separate assemblies
            builder.RegisterModule(new ConfigurationSettingsReader());
    
            builder.RegisterWebApiFilterProvider(config);
    
            // Set the dependency resolver to be Autofac
            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
    
    }
}

注册AutoFac

protected void Application_Start(object sender, EventArgs e)
 {
      AreaRegistration.RegisterAllAreas();
      GlobalConfiguration.Configure(WebApiConfig.Register);
      AutoFacConfig.Register(GlobalConfiguration.Configuration);
      //GlobalConfiguration.Configure(AutoFacConfig.Register);
  } 

配置文件
添加引用
配置autofac

    
        

注:转载请注明出处

你可能感兴趣的:(工具类,AutoFac使用)