C#asp.net核心通用工厂方法依赖注入

时间:2018-02-07 13:08:23

标签: dependency-injection asp.net-core repository-pattern

我正在使用asp.net核心,在将我的服务添加到依赖注入时,我有以下情况:

        // TODO Need to have generalized code for following Repositories
        services.AddScoped(s => s.GetRequiredService<IRepositoryFactory>().CreateRepository<Customer>(services));
        services.AddScoped(s => s.GetRequiredService<IRepositoryFactory>().CreateRepository<CustomerCategory>(services));
        services.AddScoped(s => s.GetRequiredService<IRepositoryFactory>().CreateRepository<SaleOrder>(services));

在这种情况下,我提及&#34; T&#34;显式哪个模型增长时会头痛,我的CreateRepository方法如下:

    public IRepository<T> CreateRepository<T>(IServiceCollection services) where T : class 
    {

        if (typeof(T).IsAssignableFrom(typeof(IAuditable)))
            return _provider.GetRequiredService<AuditableRepository<T>>();
        else if (typeof(T).IsAssignableFrom(typeof(IArchivable)))
            return _provider.GetRequiredService<ArchivableRepository<T>>();

        //return new Repository<T>(_provider.GetRequiredService<DbContext>());
        return _provider.GetRequiredService<Repository<T>>();
    }

我想要一些像:

services.TryAdd(ServiceDescriptor.Scoped(typeof(IRepository<>), s.GetRequiredService<IRepositoryFactory>().CreateRepository<>(services)));

提前完成。

1 个答案:

答案 0 :(得分:0)

这里可以使用的一个解决方案是为控制器实现通用基类。在通用控制器库中,您可以设置一个属性来保存存储库。当使用ASP.Net Core作为Web API时,这很有效。