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; }
3控制器里使用的例子
IUserService userService; public HomeController(IUserService _userSerivce) { userService=_userServicve; }