NetCore3.0实现自定义IOC容器注入
1.获取所有相关业务程序集aaa
publicstatic List<Assembly> GetFrameworkAssemblys(){var list = new List<Assembly>();
var deps = DependencyContext.Default;
var libs = deps.CompileLibraries;
foreach (var lib in libs)
{
if (!lib.Serviceable && lib.Type != "package" && lib.Name.StartsWith("FastCloud"))
{
var assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(lib.Name));
list.Add(assembly);
}
}
return list;
}
2.对所有Component组件注册
publicclassInjectContext {
privatestatic ContainerBuilder Container;
publicstaticvoidInit()
{
InjectFrameWork();
}
publicstaticvoidInjectFrameWork()
{
Container = new ContainerBuilder();
//获框架取所有程序集
List<Assembly> assemblies = CloudUtil.GetFrameworkAssemblys();
//注入框架所有Component组件
Container.RegisterAssemblyTypes(assemblies.ToArray(), typeof(Component), true);
Container.Build(CotainerEnum.BuidlModel.OverWrite);
}
publicstaticobjectResolve(Type Type, CotainerEnum.TypeEqual TypeEqual = CotainerEnum.TypeEqual.Ref)
{
return Container.Resolve(Type, TypeEqual);
}
publicstatic List<Type> GetRegistType(Type @Type)
{
return Container.GetRegistType(@Type);
}
}
3.实现自定义Controller工厂
publicclassCloudControllerActivator : IControllerActivator {
publicobjectCreate(ControllerContext context)
{
if (context == null)
{
thrownew ArgumentNullException(nameof(context));
}
if (context.ActionDescriptor == null)
{
thrownew ArgumentException(nameof(ControllerContext.ActionDescriptor));
}
var controllerTypeInfo = context.ActionDescriptor.ControllerTypeInfo;
if (controllerTypeInfo == null)
{
thrownew ArgumentException(nameof(context.ActionDescriptor.ControllerTypeInfo));
}
Type controllerType = controllerTypeInfo.AsType();
return InjectContext.Resolve(controllerType);
}
publicvoidRelease(ControllerContext context, object controller)
{
if (context == null)
{
thrownew ArgumentNullException(nameof(context));
}
if (controller == null)
{
thrownew ArgumentNullException(nameof(controller));
}
var disposable = controller as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
}
4.修改配置,使用自定义Controller工厂
//替换默认Controller工厂var defaultActivator = services.FirstOrDefault(c => c.ServiceType == typeof(IControllerActivator));
if (defaultActivator != null)
{
services.Remove(defaultActivator);
}
services.AddSingleton<IControllerActivator, CloudControllerActivator>();
//设置redis连接
以上是 NetCore3.0实现自定义IOC容器注入 的全部内容, 来源链接: utcz.com/z/513194.html