Net6 引入Autofac
手动注入
先引入这两个包
把默认 IOC容器替换成Autofac
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
### 注意是实例在前 然后 as 接口
builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
{
//这里放要注入的东西
builder.RegisterType<Factory>().As<IServiceFactory>().InstancePerLifetimeScope();
});
上述例子完全是手动注入,但其实原理是一样的
自动注入
声明一个空接口表示这个接口是否被注入 然后让新接口继承这个空接口(这只是其中一种还有很多种方式 如 获取类名自动注入、加Class标签注入 等等只要能拿到接口就可以)
我声明的空接口是IService
Type baseType = typeof(IService);
//var assemblies = AppDomain.CurrentDomain.GetAssemblies();//这种写法AppDomain重新启动后会丢失程序集
var assembly = Assembly.GetEntryAssembly();
builder.RegisterAssemblyTypes(assembly)
.Where(t => baseType.IsAssignableFrom(t) && t != baseType)
.AsImplementedInterfaces().InstancePerLifetimeScope();
//空接口
public interface IService
{
}
//接口
public interface IServiceFactory: IService
{
public Task<int> Get();
}
//实例
public class Factory : IServiceFactory
{
public async Task<int> Get()
{
throw new NotImplementedException();
}
}
我直接就在progrem里面调试 从容器里直接拿实例,以下结果可以看到不是Null,证明自动注入成功了
参考 https://www.cnblogs.com/tommao2618/p/15588646.html