我正在使用StructureMap进行依赖注入,并成功地将其用于我的WebApi应用程序。
ApiController已定义了存储库,并且在此存储库的构造函数中,我将注入依赖项,IMapper和DB连接字符串。
存储库在一个单独的项目(存储库层)中定义,需要由我的UI(angular和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中的控制台应用程序(控制台应用程序)中,我正在尝试使用此存储库。
请帮助我知道我是如何实现这一目标的。
答案 0 :(得分:0)
找到了这个精彩而有用的链接,帮助我理解如何在控制台应用程序中实现StructureMap: