Reputation: 702
I want to register a generic class (this class is needed because I want to implement the patterns: Repository and Unit of work) in ConfigureServices in order to get dependency injection. But I do not know how.
Here my interface:
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();
}
Its implementation:
public class BaseRepository<TEntity> : IDisposable, IBaseRepository<TEntity> where TEntity : class
{
protected CeasaContext context;
public BaseRepository(CeasaContext _context)
{
context = _context;
}
/*other methods*/
}
And what I'm trying to do:
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?}");
});
}
}
Upvotes: 3
Views: 1160
Reputation: 31
But how is about this moment?
services.AddScoped(typeof(IGenericRepository<T,TK>), typeof(GenericRepository<T, TK>));
When we have as T
, so TK
here in these brackets <>
The compiler does not allow to do this in such syntax.
Upvotes: -1
Reputation: 247088
For open generics add services as follows
services.AddTransient(typeof(IBaseRepository<>), typeof(BaseRepository<>));
Thus all dependencies on IBaseRepository<TEntity>
will be resolved to BaseRepository<TEntity>
Upvotes: 8