StructureMap MVC、存储库层和控制台/类库

本文关键字:控制台 类库 MVC 存储 StructureMap | 更新日期: 2023-09-27 17:57:38

我正在使用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中的控制台应用程序(控制台应用程序)中,我正在尝试使用此存储库。

请帮我知道我是如何做到这一点的。

StructureMap MVC、存储库层和控制台/类库

找到了这个奇妙而有用的链接,它帮助我理解了如何在控制台应用程序中实现StructureMap:

http://ardalis.com/using-structuremap-4-in-a-console-app