这是我现在拥有的接口/类结构:
BaseContentObject抽象类
public abstract class BaseContentObject : IEquatable<BaseContentObject>
{
...
}
页面具体类
public class Page : BaseContentObject
{
...
}
存储库界面
public interface IContentRepository<T>
{
// common methods for all content types
void Insert(T o);
void Update(T o);
void Delete(string slug);
void Delete(ContentType contentType, string slug);
IEnumerable<T> GetInstances();
T GetInstance(ContentType contentType, string slug);
T GetInstance(string contentType, string slug);
T GetInstance(string slug);
IEnumerable<string> GetSlugsForContentType(int limit = 0, string query = "");
ContentList GetContentItems();
bool IsUniqueSlug(string slug);
string ObjectPersistanceFolder { get; set; }
}
公共接口实现(对于继承BaseContentObject类的所有内容类)
public class XmlRepository<T> : IContentRepository<BaseContentObject>
{
public string ObjectPersistanceFolder { get; set; }
public XmlRepository()
{
ObjectPersistanceFolder = Path.Combine(XmlProvider.DataStorePhysicalPath, typeof(T).Name);
if (!Directory.Exists(ObjectPersistanceFolder))
Directory.CreateDirectory(ObjectPersistanceFolder);
}
...
}
内容特定存储库
public class XmlPagesRepository : XmlRepository<Page> { }
global.asax.cs中的Ninject规则
Bind<IContentRepository<Page>>().To<XmlPagesRepository>();
给出以下编译时错误:
*The type 'Namespace.XmlPagesRepository' cannot be used as type parameter 'TImplementation' in the generic type or method 'Ninject.Syntax.IBindingToSyntax<T>.To<TImplementation>()'. There is no implicit reference conversion from 'Namespace.XmlPagesRepository' to 'Namespace.IContentRepository<Namespace.Page>'.*
我花了很多时间搞清楚我的类和接口结构,以支持我的业务需求。现在我不知道如何克服Ninject错误。
我想在ASP.NET MVC控制器中使用这种结构,如下所示:
public IContentRepository<Page> ContentRepository { get; private set; }
public PageController(IContentRepository<Page> repository)
{
ContentRepository = repository;
}
答案 0 :(得分:2)
我认为如果您使用具体类创建测试用例,您会发现确实无法隐式地从XmlPagesRepository
转换为IContentRepository<Page>
。很难遵循,但如果转换成为可能,那么我认为使用ToMethod
绑定它:
Bind<IContentRepository<Page>>().ToMethod(x => (IContentRepository<Page>)kernel.Get<XmlPagesRepository>());
编辑:再看一下,转换是不可能的。 XmlRepository<Page>
实施IContentRepository<BaseContentObject>
而非IContentRepository<Page>
。 Page是BaseContentObject并不重要,无法进行强制转换。这不符合您的预期。
Edit2:“实现”是指实现一个接口;您实现一个接口并继承(或扩展)一个类。如果不完全理解你想要做什么,这就是我设计存储库的方式:
public interface IPageRepository : IContentRepository<Page>
{
}
public interface XmlPageRepository : IPageRepository
{
// implementation
}
您现在可以拥有多个IPageRepository实现,并使用Ninject绑定相应的实现:
Bind<IPageRepository>().To<XmlPageRepository>();