为 ConfigureServices 中的 Generic 类添加 DI

And*_*dre 3 c# dependency-injection asp.net-core

我想在 ConfigureServices 中注册一个通用类(需要这个类,因为我想实现模式:存储库和工作单元)以获得依赖注入。但是我不知道怎么做。

这是我的界面:

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();
}
Run Code Online (Sandbox Code Playgroud)

它的实现:

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

    protected CeasaContext context;

    public BaseRepository(CeasaContext _context)            
    {
        context = _context;
    }
   /*other methods*/
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试做的事情:

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?}");
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

Nko*_*osi 7

对于开放泛型添加服务如下

services.AddTransient(typeof(IBaseRepository<>), typeof(BaseRepository<>));
Run Code Online (Sandbox Code Playgroud)

因此,所有依赖项IBaseRepository<TEntity>都将被解析为BaseRepository<TEntity>