这个问题在这里已有答案:
我正在ASP.NET Core中构建解决方案体系结构 .
我在web项目中引用了 ConfigureServices()
中的声明依赖注入的存储库,你可以吗?
我认为理想只会引用服务项目,因为控制器只应该使用服务而不是存储库 .
我有这些项目:
- Web App(ASP.NET Core) - 引用所有项目 .
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddTransient<IEventsService, EventsService>();
services.AddTransient<IEventsRepository, EventsSqlRepository>();
}
public class EventsController : Controller
{
private readonly IEventsService _eventsService;
public EventsController(IEventsService eventsService)
{
_eventsService = eventsService;
}
}
- 业务(类库 - .NET标准)
Folder IServices
IEventsService
Folder Services
public class EventsService : IEventsService
{
private readonly IEventsRepository _eventsRepository;
public EventsService(IEventsRepository eventsRepository)
{
_eventsRepository = eventsRepository;
}
}
-
IRepository(类库 - .NET标准版)
-
IEventsRepository
-
Repository(类库 - .NET标准版)
-
使用E.F.访问BD
public class EventsSqlRepository : BaseRepository, IEventsRepository
{
}
-
Utils(类库 - .NET标准版)
-
实体(类库 - .NET标准版)
-
来自BD E.F.
非常感谢 !
1 回答
你的解决方案很好 . 注册应用程序依赖项的部分称为组合根,它's the only place in your application where all your dependencies should be registered. Even though it'实际放置在您应用程序的Web项目部分中,它在逻辑上是应用程序的独立部分 . 你可以在这里阅读更多相关信息:http://blog.ploeh.dk/2011/07/28/CompositionRoot/