一般注入比较麻烦,可以不依赖第三方组件命名空间注入
- using Microsoft.Extensions.DependencyInjection;
- using Newtonsoft.Json;
- using System.Reflection;
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddTransientFromNamespace(
this IServiceCollection services,
string namespaceName,
params Assembly[] assemblies
)
{
foreach (Assembly assembly in assemblies)
{
IEnumerable<Type> types = assembly.GetTypes();
types = types.Where(t => t.IsClass);
Console.WriteLine(JsonConvert.SerializeObject(types));
types = types.Where(x => (x.Namespace??"").StartsWith(namespaceName, StringComparison.InvariantCultureIgnoreCase));
//types.Where(x =>
// x.IsClass
// && x.Namespace!.StartsWith(namespaceName, StringComparison.InvariantCultureIgnoreCase)
//);
foreach (Type? type in types)
{
if (services.All(x => x.ServiceType != type))
{
_ = services.AddTransient(type);
}
}
}
return services;
}
public static IServiceCollection AddSingletonFromNamespace(
this IServiceCollection services,
string namespaceName,
params Assembly[] assemblies
)
{
foreach (Assembly assembly in assemblies)
{
IEnumerable<Type> types = assembly
.GetTypes()
.Where(x =>
x.IsClass
&& x.Namespace!.StartsWith(namespaceName, StringComparison.InvariantCultureIgnoreCase)
);
foreach (Type? type in types)
{
if (services.All(x => x.ServiceType != type))
{
_ = services.AddSingleton(type);
}
}
}
return services;
}
}
使用方法
class AppAssembly
{
public static Assembly ExecutingAsssembly => Assembly.GetExecutingAssembly();
}
private static readonly IHost appHost = Host.CreateDefaultBuilder()
.ConfigureAppConfiguration(c =>
{
c.SetBasePath(AppContext.BaseDirectory);
})
.ConfigureServices(
(_, services) =>
{
services.AddLogging(loggerBuilder =>
{
var nlog_configfile = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "NLog.config");
LogManager.Configuration = new XmlLoggingConfiguration(nlog_configfile);
NLog.ScopeContext.PushProperty("workername", "client");
loggerBuilder.ClearProviders();
loggerBuilder.AddNLog(LogManager.Configuration);
});
// 放类 IHostedService是后台服务类.NetCore功能
services.AddHostedService<HostedService >();
//放接口与实现类
services.AddSingleton<IDemo, Demo>();
//重点 ,命名空间注册...
services.AddTransientFromNamespace("Demo.AAAA",AppAssembly.ExecutingAsssembly);
//重点 ,命名空间指定dll...
var assemblyPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Demo.BBB.dll");
services.AddTransientFromNamespace("Demo.BBB", Assembly.LoadFrom(assemblyPath));
services.BuildServiceProvider();
}
) .Build();
标签:Core,Assembly,namespaceName,IServiceCollection,static,services,NET,type,types
From: https://blog.csdn.net/qq_31136349/article/details/139357903