在ConfigureServices中为Generic类添加DI

时间:2018-06-10 11:24:19

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

我想在ConfigureServices中注册一个泛型类(需要这个类,因为我想实现模式:Repository和Unit of work)以获得依赖注入。但我不知道如何。

这是我的界面:

public interface IBaseRepository<TEntity> where TEntity : class
{
    void Add(TEntity obj);

    TEntity GetById(int id);

    IEnumerable<TEntity> GetAll();

    void Update(TEntity obj);

    void Remove(TEntity obj);

    void Dispose();
}

其实施:

public class BaseRepository<TEntity> : IDisposable, IBaseRepository<TEntity> where TEntity : class
{

    protected CeasaContext context;

    public BaseRepository(CeasaContext _context)            
    {
        context = _context;
    }
   /*other methods*/
}

我正在尝试做什么:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        var connection = @"Data Source=whatever;Initial Catalog=Ceasa;Persist Security Info=True;User ID=sa;Password=xxx;MultipleActiveResultSets=True;";

        services.AddDbContext<CeasaContext>(options => options.UseSqlServer(connection));

        services.AddTransient<BaseRepository, IBaseRepository>();

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

1 个答案:

答案 0 :(得分:3)

对于开放式泛型添加服务,如下所示

services.AddTransient(typeof(IBaseRepository<>), typeof(BaseRepository<>));

因此IBaseRepository<TEntity>上的所有依赖关系都将解析为BaseRepository<TEntity>