官方建议使用内置容器,但有些功能并不支持,如下:
- 属性注入
- 基于名称的注入
- 子容器
- 自定义生存期管理
- Func<T> 支持
所以可以使用其他第三方IOC容器,如Autofac,下面为学习使用记录
一、首先准备了一个接口和其实现类
public interface ITestService {string ShowMsg(); }
public class TestService: ITestService {public string ShowMsg(){return "test123";} }
二、安装Nuget 包
Autofac
Autofac.Extensions.DependencyInjection
三、在 Startup.ConfigureServices 中配置容器
注:使用第三方容器,Startup.ConfigureServices 必须返回 IServiceProvider。
第一种方式,使用AutofacModule配置文件,原来代码修改为:
public IServiceProvider ConfigureServices(IServiceCollection services) {services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);// Add Autofacvar containerBuilder = new ContainerBuilder();containerBuilder.RegisterModule<AutofacModule>();containerBuilder.Populate(services);var container = containerBuilder.Build();return new AutofacServiceProvider(container); }
AutofacModule类如:
public class AutofacModule: Module {protected override void Load(ContainerBuilder builder){builder.RegisterType<TestService>().As<ITestService>();
//...........} }
第二种方式
Startup.ConfigureServices如下修改
public IServiceProvider ConfigureServices(IServiceCollection services) {services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);// Add Autofacvar containerBuilder = new ContainerBuilder();//containerBuilder.RegisterModule<AutofacModule>();
//自动注册该程序集下的所有接口//netcore_autofac 为程序集命名空间//InstancePerLifetimeScope:同一个Lifetime生成的对象是同一个实例//SingleInstance:单例模式,每次调用,都会使用同一个实例化的对象;每次都用同一个对象;//InstancePerDependency:默认模式,每次调用,都会重新实例化对象;每次请求都创建一个新的对象;containerBuilder.RegisterAssemblyTypes(Assembly.Load("netcore_autofac")).AsImplementedInterfaces().InstancePerLifetimeScope();containerBuilder.Populate(services);var container = containerBuilder.Build();return new AutofacServiceProvider(container); }
其他Autofac在.net core 的使用,请参考官方文档:https://docs.autofac.org/en/latest/integration/aspnetcore.html