在ConfigureServices中为通用类添加DI

其他

我想在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();
}

其实现:

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?}");
        });
    }
}
恩科西

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

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章