NetCore3.0实现自定义IOC容器注入
2021-04-19 22:29
标签:cloud script compile action 自定义 ast reg star ini
在之前的ASP.NET MVC实现依赖注入一文中,通过替换默认的ControllerFactory来达到对Controller生命周期的拦截,实现自定义的对象注入,在NetCore3.0中需要重新实现,步骤如下: 1.获取所有相关业务程序集 2.对所有Component组件注册 3.实现自定义Controller工厂 4.修改配置,使用自定义Controller工厂 NetCore3.0实现自定义IOC容器注入 标签:cloud script compile action 自定义 ast reg star ini 原文地址:https://www.cnblogs.com/lonelyxmas/p/12264594.html
public
static
List GetFrameworkAssemblys()
{
var
list =
new
List();
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;
}
public
class
InjectContext
{
private
static
ContainerBuilder Container;
public
static
void
Init()
{
InjectFrameWork();
}
public
static
void
InjectFrameWork()
{
Container =
new
ContainerBuilder();
//获框架取所有程序集
List assemblies = CloudUtil.GetFrameworkAssemblys();
//注入框架所有Component组件
Container.RegisterAssemblyTypes(assemblies.ToArray(),
typeof
(Component),
true
);
Container.Build(CotainerEnum.BuidlModel.OverWrite);
}
public
static
object
Resolve(Type Type, CotainerEnum.TypeEqual TypeEqual = CotainerEnum.TypeEqual.Ref)
{
return
Container.Resolve(Type, TypeEqual);
}
public
static
List
{
return
Container.GetRegistType(@Type);
}
}
public
class
CloudControllerActivator : IControllerActivator
{
public
object
Create(ControllerContext context)
{
if
(context ==
null
)
{
throw
new
ArgumentNullException(nameof(context));
}
if
(context.ActionDescriptor ==
null
)
{
throw
new
ArgumentException(nameof(ControllerContext.ActionDescriptor));
}
var
controllerTypeInfo = context.ActionDescriptor.ControllerTypeInfo;
if
(controllerTypeInfo ==
null
)
{
throw
new
ArgumentException(nameof(context.ActionDescriptor.ControllerTypeInfo));
}
Type controllerType = controllerTypeInfo.AsType();
return
InjectContext.Resolve(controllerType);
}
public
void
Release(ControllerContext context,
object
controller)
{
if
(context ==
null
)
{
throw
new
ArgumentNullException(nameof(context));
}
if
(controller ==
null
)
{
throw
new
ArgumentNullException(nameof(controller));
}
var
disposable = controller
as
IDisposable;
if
(disposable !=
null
)
{
disposable.Dispose();
}
}
}
//替换默认Controller工厂
var
defaultActivator = services.FirstOrDefault(c => c.ServiceType ==
typeof
(IControllerActivator));
if
(defaultActivator !=
null
)
{
services.Remove(defaultActivator);
}
services.AddSingleton
上一篇:css通用样式
下一篇:C#设置和获取系统环境变量