這並沒有什麼意義。你會問容器IRepository
,那麼它如何知道泛型類型參數應該是什麼樣的,以便它能給你一個MyRepository<,>
?
所以當要求返回這樣一個對象:
public class MyService
{
private IRepository<Something, SomethingElse> _repo;
public MyService(IRepository<Something, SomethingElse> repo)
{
// Container will actually give us MyRepository<Something, SomethingElse>
_repo = repo;
}
}
我希望之一:
services.AddTransient(typeof(IRepository<,>), typeof(MyRepository<,>));
,或者,如果你的資料庫不需要是通用的(我不知道了解爲什麼它會需要通用參數,因爲它是),那麼我會想到這一點:
services.AddTransient(typeof(IRepository), typeof(MyRepository));
然而,由於沒有這裏涉及到仿製藥,你可以用另一種形式來實現同樣的事情少打字:
services.AddTransient<IRepository, MyRepository>();
所以,真正的答案是解決你的接口/類設計。顯示更多的執行他們會有所幫助。
UPDATE
你的執行工作必須:
類實現:
public class MyRepository<TEntity, TContext> : IRepository<TEntity, TContext>
where TEntity : class
where TContext : IDbContext, new()
{
...
}
接口:
public interface IRepository<TEntity, TContext> : IDisposable
where TEntity : class
where TContext : IDbContext, new()
{
...
}
這裏是我正在做我的核心庫的DependencyInjection:services.AddScoped (); –
lucas
你(lucas)和OP之間有明顯的區別。請注意開放式泛型。你仍然在覈心中使用DI框架,核心只是公開一些接口來輕鬆掛接它。 –
我仍然會繼續刪除Ninject,並添加諸如Autofac,StructureMap或LightInject之類的東西。但是,該文檔指出,功能非常有限,我認爲這不會延伸到開放泛型。我喜歡結構映射,因爲它是基於約定的程序集掃描 –