【发布时间】:2017-01-09 12:21:06
【问题描述】:
我正在创建一个新的 web api 项目。除了 web api 项目,我还使用了另外两个类库项目,如下所示:
MyBlog.API (Web API project)
MyBlog.Services (Class library)- Contains additional business logic
MyBlog.Repositories (Class library) - contains all database related operations
在 API 项目中,我添加了 Services 项目的引用,在 Services 项目中,我添加了 Repositories 项目的引用,因此 API 将调用服务,服务将调用存储库,如下所示:
API > Services > Repositories
我不想直接从我的 api 控制器调用存储库,它们将通过服务调用。所以我没有在 api 项目中添加存储库项目引用。
现在我正在我的 api 项目中实现 unity.webapi 依赖注入。下面是实现DI的代码:
存储库代码:
namespace MyBlogs.Repositories
{
public interface ITestRepository
{
string Get();
}
}
namespace MyBlogs.Repositories
{
public class TestRepository:ITestRepository
{
public string Get()
{
return "test";
}
}
}
带有 DI 实现的服务代码:
namespace MyBlogs.Services
{
public interface ITestService
{
string Get();
}
}
namespace MyBlogs.Services
{
public class TestService : ITestService
{
private ITestRepository testRepository;
public TestService(ITestRepository testRepositoryParam)
{
this.testRepository = testRepositoryParam;
}
public string Get()
{
return this.testRepository.Get();
}
}
}
控制器代码:
public class ValuesController : ApiController
{
private ITestService testService;
public ValuesController(ITestService testServiceParam)
{
this.testService = testServiceParam;
}
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { this.testService.Get() };
}
}
最后是 unityconfig 文件:
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
container.RegisterType<ITestService, TestService>();
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
}
}
现在我在这里面临这个问题,因为我没有在我有这个 unityconfig 文件的 api 项目中添加存储库项目引用,所以我如何在统一中注册 ITestRepository 和 TestRepository,类似于 ITestService 和 TestService?有什么方法可以在不添加项目引用的情况下在其他地方注册我的存储库项目的依赖项?或者如果我将尝试在服务项目中添加统一性,那么它将如何注册??
我已经在web api项目的global.asax中注册了unityConfig:
protected void Application_Start()
{
UnityConfig.RegisterComponents();
}
【问题讨论】:
-
mmm .. 我认为您必须在 webapi 项目或控制台项目中调用 Unity ..
-
理论上你可以在 MyBlogs.Services 程序集中定义另一个 Unity 配置,它知道存储库并注册它。这样做你不会有从 webapi 到存储库的引用使 MyBlogs.Services 中的另一个 UnityConfig 在那里注册你的存储库类型,然后 ServicesUnityConfig.RegsiterComponents() UnityConfig.RegisterComponents();
-
@eranotzap 看起来不错,我会试一试。谢谢。
标签: asp.net-mvc asp.net-web-api unity-container