【发布时间】:2023-03-20 13:38:01
【问题描述】:
我正在使用 StructureMap 进行依赖注入,并在我的 WebApi 应用程序中成功使用它。
ApiController 定义了存储库,并且在此存储库的构造函数中,我正在注入依赖项、IMapper 和 DB 连接字符串。
存储库在一个单独的项目(存储库层)中定义,我的 UI(角度和 WebApi)以及其他解决方案(在本例中为示例控制台应用程序)需要使用该项目。我无法找到通过这些依赖项在我的控制台应用程序中实例化存储库的方法。
在 MVC/WebApi 世界中,控制器创建(工厂)和存储库引导发生在内部......如果我错了,请纠正我。
如果我们要像这个场景一样使用同一个存储库,请给我一些想法。我对 StructureMap DI 很陌生。
ClientRepository.cs
public class ClientRepository : IClientRepository
{
private IMapper _mapper;
private string _connectionString;
private const string CLIENTSCACHE = "clients";
private MemoryCache _memoryCache = MemoryCache.Default;
public ClientRepository(IMapper mapper, string connectionString)
{
_mapper = mapper;
_connectionString = connectionString;
}
public List<ClientFileTreeViewModel> GetClients()
{
//DB connection
//transform using Automapper to the viewmodel type and return
}
//some other code here
}
DefaultRegistry.cs
public DefaultRegistry()
{
var profiles = from t in typeof(DefaultRegistry).Assembly.GetTypes()
where typeof(Profile).IsAssignableFrom(t)
select (Profile)Activator.CreateInstance(t);
var config = new MapperConfiguration(cfg =>
{
foreach (var profile in profiles)
{
cfg.AddProfile(profile);
}
});
var mapper = config.CreateMapper();
For<IConfigurationProvider>().Use(config);
For<IMapper>().Use(mapper);
RegisterRepositories(mapper);
}
private void RegisterRepositories(IMapper mapper)
{
For<IClientRepository>().Use<ClientRepository>()
.Ctor<IMapper>().Is(mapper)
.Ctor<string>().Is(ConfigurationManager.ConnectionStrings["DeIdentifyDBConnection"].ConnectionString);
}
}
ClientController.cs
public class ClientController : ApiController
{
IClientRepository _repository;
public ClientController(IClientRepository repo)
{
_repository = repo;
}
//some other code
}
现在在 Program.cs 的控制台应用程序(控制台应用程序)中,我正在尝试利用此存储库。
请帮助我了解我是如何实现这一目标的。
【问题讨论】:
标签: c# angularjs asp.net-web-api dependency-injection structuremap