gpt4 book ai didi

c# - 在 ConfigureServices 中为通用类添加 DI

转载 作者:行者123 更新时间:2023-11-30 20:25:55 24 4
gpt4 key购买 nike

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

这是我的界面:

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>

关于c# - 在 ConfigureServices 中为通用类添加 DI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50783183/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com