在泛型类上注册DI

时间:2018-03-30 13:00:55

标签: c# logging dependency-injection asp.net-core-2.0

我有一个泛型类型,我试图注入记录器,我尝试了不同的组合,如底部,找不到解决方案。

public interface IFoo : IBoo
{

}

public class Foo<TResponse> : IFoo where TResponse : IFooResponse
{
     private readonly IAppSettings appSettings;
     private readonly ILogger<IFoo<TResponse>> logger;

     public Foo(IAppSettings appSettings, ILogger<Foo<TResponse>> logger)
    {
            this.appSettings = appSettings;            
            this.logger = logger;
    }
}


services.AddScoped<IFoo, Foo>();

services.AddScoped(typeof(IFoo<>), typeof(Foo<>));

services.AddScoped(s => new IFoo<IFooResponse>(appSettings, s.GetService<Serilog.ILogger<IFoo>>));

1 个答案:

答案 0 :(得分:-1)

我将为您提供一个如何使用Entity Framework创建服务的简单示例。首先我们有模型。

public class Product
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ProductID { get; set; }

    public string Name { get; set; }
}

然后我们创建界面

public interface IProductsRepository
{
    void DeleteProduct(int id);
}

然后我们创建存储库

public class ProductsRepository : IProductsRepository
{
    private readonly WebApplication8.Data.ApplicationDbContext _context;
    public ProductsRepository(ApplicationDbContext context)
    {
        _context = context;
    }

    public void DeleteProduct(int id)
    {
        Product product = _context.Product.Find(id);
        if (product != null)
        {
            _context.Product.Remove(product);
            _context.SaveChanges();
        }
    }
}

现在我们可以在Service Collection中添加我们的服务

services.AddTransient<IProductsRepository, ProductsRepository>();

最后,您可以使用约束器获取服务的实例

private IProductsRepository _productsRepository;
public Constractor(IProductsRepository productsRepository)
{
    _productsRepository = productsRepository;
}

我希望它有所帮助