C# SimpleIOC与泛型
我试图泛化一些代码,以便在项目之间使用,但从模板类生成实例时遇到了一些问题C# SimpleIOC与泛型,c#,generics,simpleioc,C#,Generics,Simpleioc,我试图泛化一些代码,以便在项目之间使用,但从模板类生成实例时遇到了一些问题 public class GenericRepository<TEntity, TContext> : IGenericRepository<TEntity>, IDisposable where TEntity : class where TContext : DbContext, new () { protected TContext Context; pub
public class GenericRepository<TEntity, TContext> : IGenericRepository<TEntity>, IDisposable
where TEntity : class
where TContext : DbContext, new ()
{
protected TContext Context;
public GenericRepository()
{
Context = new TContext();
}
public virtual TEntity Create()
{
return Context.Set<TEntity>().Create();
}
// etc.
}
public interface IPlan
{
int PlanId { get; set; }
string Name { get; set; }
DateTime Modified { get; set; }
DateTime Created { get; set; }
event PropertyChangedEventHandler PropertyChanged;
}
public partial class Session : DataErrorInfo, INotifyPropertyChanged, IPlan
{
// Stuff to implement IPlan
}
公共类GenericRepository:IGenericRepository,IDisposable
地点:班级
其中TContext:DbContext,new()
{
受保护的TContext上下文;
公共通用存储库()
{
Context=新的TContext();
}
公共虚拟空间创建()
{
返回Context.Set().Create();
}
//等等。
}
公共接口IPlan
{
int PlanId{get;set;}
字符串名称{get;set;}
已修改日期时间{get;set;}
已创建日期时间{get;set;}
事件属性ChangedEventHandler属性Changed;
}
公共部分类会话:DataErrorInfo、INotifyPropertyChanged、IPlan
{
//实现IPlan的工具
}
IPlan和通用存储库位于公共代码库中,会话是特定于项目的。所以我希望能够做到这样:
// These both work correctly
SimpleIoc.Default.Register<IPlan, Session>();
SimpleIoc.Default.Register<IGenericRepository<Session>, GenericRepository<Session, EMTVSEntities>>();
// Tried this one ...
SimpleIoc.Default.Register<IGenericRepository<IPlan>, GenericRepository<Session, EMTVSEntities>>();
//这两个都能正常工作
SimpleIoc.Default.Register();
SimpleIoc.Default.Register();
//试过这个。。。
SimpleIoc.Default.Register();
最终我想要的是能够称之为最后一个,并得到这样的上下文
var ctx = ServiceLocator.Current.GetInstance<IGenericRepository<IPlan>>();
var ctx=ServiceLocator.Current.GetInstance();
但我收到以下消息:无法将类型为“GenericRepository2[Session,emtSenties]”的对象强制转换为类型为“IGenericRepository
1[IPlan]”
我知道它不能匹配这两种类型来执行案例,但是有没有一种方法可以从使用模板类型GenericRepository的接口标识的实例中获取特定实例?您使用的是什么库?GalasoFT.MVVMLIO.IOC。SimpleIoc?是的,GalasOf.MVVMLIT.IO.SimuliCII会考虑切换到不同的IOC框架,如果它完成了我需要做的事情,你在用什么图书馆?GalasoFT.MVVMLI.IOC。SimpleIoc?是的,GalasOf.MVVMLIt.IO.SimuliCII将考虑切换到不同的IOC框架,如果它完成了我需要做的事情,尽管如此。