标签:dep global conf 获取 相同 contain str uil register
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); var builder = new ContainerBuilder(); // 注册所有的Controller builder.RegisterControllers(Assembly.GetExecutingAssembly()); //// RegisterType方式: //builder.RegisterType<UserService>().As<IService>().InstancePerRequest(); //// Register方式: //builder.Register(c => new UserService()).AsSelf().InstancePerDependency(); var IServices = Assembly.Load("BLL"); var IRepository = Assembly.Load("DAL"); //根据名称约定(服务层的接口和实现均以Service结尾),实现服务接口和服务实现的依赖 builder.RegisterAssemblyTypes(IServices, IServices).Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces().InstancePerRequest(); builder.RegisterAssemblyTypes(IRepository, IRepository).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces(); // 把容器装入到微软默认的依赖注入容器中 var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); }
BLL
public interface IService
{
string Test();
}
public class UserService:IService
{
private IRepository repository;
public UserService(IRepository repository)
{
this.repository = repository;
}
public string Test()
{
return this.repository.GetUser();
}
}
DAL
public interface IRepository { string GetUser(); }
public class UserRepository:IRepository { public string GetUser() { return "获取到了用户"; } }
Controller
private readonly IService _testService; public TestController(IService testService, IService testServiceA) { if (testService == testServiceA)//判断不同生命周期注入的对象是否相同 { } _testService = testService; }
标签:dep global conf 获取 相同 contain str uil register
原文地址:https://www.cnblogs.com/chenyishi/p/9157064.html