Vic*_*tos 2 c# asp.net-mvc dependency-injection asp.net-core
我正在尝试在我的软件上实现Core的依赖注入,以取代Ninject并将所有内容更新为我们的新技术.
顺便说一下,我在一些通用的接口上遇到了问题.对于这种情况,我直接得到一个异常,即注入器无法创建我的类的实例.
我插在一个样品盒的小片上面,这让我着火了.
services.AddTransient(typeof(IRepository), typeof(MyRepository<,>))
Run Code Online (Sandbox Code Playgroud)
这样正确吗?我怎样才能做到这一点?
课程实施:
public class MyRepository<TEntity, TContext> : IRepositoryBase
where TEntity : class
where TContext : IDbContext, new()
{
...
}
Run Code Online (Sandbox Code Playgroud)
接口:
public interface IRepository : IDisposable
{
...
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
这没有多大意义.你将要求容器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;
}
}
Run Code Online (Sandbox Code Playgroud)
我希望:
services.AddTransient(typeof(IRepository<,>), typeof(MyRepository<,>));
Run Code Online (Sandbox Code Playgroud)
或者,如果你的仓库不需要是通用的(我不明白为什么它会需要2个通用参数,因为它是),那么我会想到这一点:
services.AddTransient(typeof(IRepository), typeof(MyRepository));
Run Code Online (Sandbox Code Playgroud)
但是,由于此处不涉及泛型,您可以使用替代形式以较少的输入实现相同的功能:
services.AddTransient<IRepository, MyRepository>();
Run Code Online (Sandbox Code Playgroud)
所以答案是解决您的界面/类设计.显示更多的实现将有所帮助.
UPDATE
您的实施需要:
课程实施:
public class MyRepository<TEntity, TContext> : IRepository<TEntity, TContext>
where TEntity : class
where TContext : IDbContext, new()
{
...
}
Run Code Online (Sandbox Code Playgroud)
接口:
public interface IRepository<TEntity, TContext> : IDisposable
where TEntity : class
where TContext : IDbContext, new()
{
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
200 次 |
| 最近记录: |