【问题标题】:Add DI for a Generic class in ConfigureServices在 ConfigureServices 中为 Generic 类添加 DI
【发布时间】:2018-06-10 11:24:18
【问题描述】:

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

【问题讨论】:

  • 您可能想阅读this post,关于在 ASP.NET Core 中使用 UoW 和 Repository 与 Entity Framework Core
  • 我会读,谢谢

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


【解决方案1】:

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

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

因此对IBaseRepository&lt;TEntity&gt; 的所有依赖都将解析为BaseRepository&lt;TEntity&gt;

【讨论】:

    【解决方案2】:

    但是这一刻怎么样?

    services.AddScoped(typeof(IGenericRepository<T,TK>), typeof(GenericRepository<T, TK>));
    

    当我们有T,所以TK 在这些括号中&lt;&gt; 编译器不允许在这样的语法中这样做。

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    相关资源
    最近更新 更多