Autofac使用

1引用dll

 autofac.dll 

 autofac.integration.mvc.dll

 protected void Application_Start()
        {
              var builder = RegisterService();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(builder.Build()));

        }


   private ContainerBuilder RegisterService()
        {
            var builder = new ContainerBuilder();

            var baseType = typeof(IDependency);
            var assemblys = AppDomain.CurrentDomain.GetAssemblies().ToList();
            var AllServices = assemblys
                .SelectMany(s => s.GetTypes())
                .Where(p => baseType.IsAssignableFrom(p) && p != baseType);

            builder.RegisterControllers(assemblys.ToArray());

            builder.RegisterAssemblyTypes(assemblys.ToArray())
                   .Where(t => baseType.IsAssignableFrom(t) && t != baseType)
                   .AsImplementedInterfaces().InstancePerLifetimeScope();
            return builder;
        }
2global.asax.cs里配置

3控制器里使用的例子

IUserService userService;
public HomeController(IUserService _userSerivce)
{
    userService=_userServicve;
}
 
例子

 

posted @ 2016-06-16 16:33  奎宇工作室  阅读(173)  评论(0编辑  收藏  举报