我必须重写一个旧的ASP经典Web应用程序。 我选择了三个层次的体系结构(层/项目=层层次)
在Web层中,我使用此类简单的DI来管理服务层注入
[assembly: OwinStartupAttribute(typeof(MyApp.Startup))]
namespace MyApp
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
var services = new ServiceCollection();
ConfigureServices(services);
var resolver = new DefaultDependencyResolver(services.BuildServiceProvider());
DependencyResolver.SetResolver(resolver);
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersAsServices(typeof(Startup).Assembly.GetExportedTypes()
.Where(t => !t.IsAbstract && !t.IsGenericTypeDefinition)
.Where(t => typeof(IController).IsAssignableFrom(t)
|| t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)));
services.AddSingleton<IAuthenticationService, AuthenticationService>();
services.AddSingleton<IChannelService, ChannelService>();
//add more DI services here...
}
}
}
Web层对数据层一无所知,那么如何注入数据层类呢?我至少需要在服务层中提供可用的数据层,但是如何在服务层中创建一个类似于上面的类?
编辑:注释中的可能解决方案现已删除。 我也在这里找到了一篇有趣的文章,关于这个论点
https://asp.net-hacker.rocks/2017/03/06/using-dependency-injection-in-multiple-projects.html
在服务层中创建扩展类,该扩展类将数据层依赖项添加到IServiceCollection实例
namespace MyApp.Service
{
public static class IServiceCollectionExtension
{
public static IServiceCollection AddDataQueries(this IServiceCollection services)
{
//services.AddTransient<IQuery, Query>();
//...add here DI of other data services
return services;
}
}
}
和启动类中的
services.AddSingleton<IAuthenticationService, AuthenticationService>();
services.AddSingleton<IChannelService, ChannelService>();
//add more DI services here...
services.AddDataQueries();
//add DI for other layers