1.首先引入Scrutor包
2.在App.xaml.cs中注册
csharp
protected override IContainerExtension CreateContainerExtension()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddMemoryCache();
serviceCollection.AddAutoMapper();
serviceCollection.RegisteServices();
return new DryIocContainerExtension(new Container(CreateContainerRules())
.WithDependencyInjectionAdapter(serviceCollection));
}
3.ServiceExtension类:
csharp
public static void RegisteServices(this IServiceCollection services)
{
services.Scan(scan =>
{
scan.FromAssemblyOf<GlobalValues>()
.AddClasses(classes => classes.Where(t => t.Name.EndsWith("Service", StringComparison.OrdinalIgnoreCase)))
.AsImplementedInterfaces()
.WithScopedLifetime();
});
}
如果没有一接口多实现的情况
这段代码就满足了
如果有一接口多实现的情况,需要额外加一部分代码
csharp
public static void RegisteServices(this IServiceCollection services)
{
var uploadWay = ConfigurationManager.AppSettings["UploadWay"];//自定义字段包含在命名的service中用来判断具体注册那个service
services.Scan(scan =>
{
scan.FromAssemblyOf<GlobalValues>()
.AddClasses(classes => classes.Where(t => t.Name.EndsWith("Service", StringComparison.OrdinalIgnoreCase)))
.AsImplementedInterfaces()
.WithScopedLifetime();
if (!string.IsNullOrEmpty(uploadWay))
{
scan.FromAssemblyOf<GlobalValues>()
.AddClasses(classes => classes.Where(t =>
t.Name.EndsWith("Service", StringComparison.OrdinalIgnoreCase) &&
t.Name.Contains(uploadWay, StringComparison.OrdinalIgnoreCase)))
.AsImplementedInterfaces().WithScopedLifetime();
}
});
}