此类为扩展注入类,使用autofuc 仅供参考
注入接口和实现。
使用方法:
//配置项调用ConfigContainer
cs
public void ConfigureContainer(ContainerBuilder builder)
{
TestMicroService.ConfigContainer(builder);
}
//service调用RegisteApiController
cs
public void ConfigureServices(IServiceCollection services)
{
TestMicroService
.RegisteApiController(services)
.AddApiExplorer()
.AddAuthorization();
}
cs
{
public static class TestMicroService
{
private static readonly string START_PATH = AppContext.BaseDirectory;
private static readonly string API_CONTROLLER_PARTTERN = "Test.*.ApiController.dll";
private static readonly string SERVICE_INTERFACE_PARTTERN = "Test.*.Service.dll";
private static readonly string SERVICE_IMPLEMENT_PARTTERN = "Test.*.ServiceImpl.dll";
private static readonly string DAO_INTERFACE_PARTTERN = "Test.*.Dao.dll";
private static readonly string DAO_IMPLEMENT_PARTTERN = "Test.*.DaoImpl.dll";
public static IMvcCoreBuilder RegisteApiController(IServiceCollection services)
{
Assembly[] apiControllerAssemblies = AssemblyUtils.ListAssemblies(START_PATH, API_CONTROLLER_PARTTERN);
return services.AddMvcCore().ConfigureApplicationPartManager(delegate (ApplicationPartManager c)
{
Assembly[] array = apiControllerAssemblies;
foreach (Assembly assembly in array)
{
c.ApplicationParts.Add(new AssemblyPart(assembly));
}
ControllerFeature controllerFeature = new ControllerFeature();
c.PopulateFeature(controllerFeature);
services.AddSingleton(controllerFeature.Controllers.Select((TypeInfo t) => t.AsType()).ToArray());
});
}
public static void ConfigContainer(this ContainerBuilder builder)
{
Assembly[] array = AssemblyUtils.ListAssemblies(START_PATH, SERVICE_INTERFACE_PARTTERN);
Assembly[] array2 = AssemblyUtils.ListAssemblies(START_PATH, SERVICE_IMPLEMENT_PARTTERN);
Assembly[] array3 = AssemblyUtils.ListAssemblies(START_PATH, DAO_INTERFACE_PARTTERN);
Assembly[] array4 = AssemblyUtils.ListAssemblies(START_PATH, DAO_IMPLEMENT_PARTTERN);
if (array.Length != array2.Length || array3.Length != array4.Length)
{
throw new Exception("init error.some service or dao assembly are missing...");
}
Assembly[] array5 = array2;
foreach (Assembly assembly in array5)
{
string interfaceName = assembly.GetName().Name!.Replace("Impl", "");
Assembly assembly2 = array.FirstOrDefault((Assembly c) => c.GetName().Name == interfaceName);
if (assembly2 != null)
{
(from t in builder.RegisterAssemblyTypes(assembly2, assembly)
where t.Name.EndsWith("ServiceImpl")
select t).AsImplementedInterfaces();
}
}
array5 = array4;
foreach (Assembly assembly3 in array5)
{
string daoInterfaceName = assembly3.GetName().Name!.Replace("Impl", "");
Assembly assembly4 = array3.FirstOrDefault((Assembly c) => c.GetName().Name == daoInterfaceName);
if (assembly4 != null)
{
(from t in builder.RegisterAssemblyTypes(assembly4, assembly3)
where t.Name.EndsWith("DaoImpl")
select t).AsImplementedInterfaces();
}
}
}
}
}