我必须重写一个旧的 asp 经典 web 应用程序。我选择了三个层次的架构(层/项目=层级)
- Web:视图和控制器,尽可能的精简。参考服务层项目。
- 服务:业务逻辑。参考数据层项目。
- 数据:ado 网络查询、数据库连接和事务管理。不参考其他项目
在 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