请有人帮助我,因为我很困惑。
我有一个这样的实体:
public class Code
{
public int ID { get; set; }
public int UserID { get; set; }
public string CodeText { get; set; }
}
和这样的界面:
public interface ICodeRepository
{
IQueryable<Code> Codes { get; }
void AddCode(Code code);
void RemoveCode(Code code);
Code GetCodeById(int id);
}
和一个像这样的存储库:
public class SQLCodeRepository : ICodeRepository
{
private EFSQLContext context;
public SQLCodeRepository()
{
context = new EFSQLContext();
}
public IQueryable<Code> Codes
{
get { return context.Codes; }
}
public void AddCode(Code code)
{
context.Codes.Add(code);
context.SaveChanges();
}
public void RemoveCode(Code code)
{
context.Codes.Remove(code);
context.SaveChanges();
}
public Code GetCodeById(int id)
{
return context.Codes.Where(x => x.ID == id).FirstOrDefault();
}
}
和这样的上下文:
public class EFSQLContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Code> Codes { get; set; }
public DbSet<PortfolioUser> PortfolioUsers { get; set; }
}
如果我像这样声明我的 Controller :
public class SearchController : Controller
{
private ICodeRepository cRepo;
public SearchController(ICodeRepository codeRepository)
{
cRepo = codeRepository;
}
}
然后尝试执行cRepo.GetCodeById(1)
什么也没有发生。但是,如果我声明私有(private)ICodeRepository rep = new SQLCodeRepository
,然后调用rep.GetCodeById(1)
,我可以看到正在调用的存储库中的方法。
我做错了什么?
最佳答案
从构造函数签名来看,您将进行一些依赖项注入(inject)。您缺少的步骤是使用 CaSTLe Windsor 等工具设置 DI 容器。然后,您将 MVC 解析器配置为使用 DI 容器来为您提供 ICodeRepository
的正确实现。
参见this
您需要创建一个实现 IDependencyResolver
和 IDependencyScope
的解析器以及一个继承DefaultControllerFactory
的 Controller 工厂
一旦有了这些,您就可以执行以下操作:
MyContainer container; // this needs to be a class level member of the asax
var configuration = GlobalConfiguration.Configuration;
container = new MyContainer() // may need additional stuff here depending on DI tool used
configuration.DependencyResolver = new MyDependancyResolver(container);
var mvcControllerFactory = new MyFactory(container.Kernel);
ControllerBuilder.Current.SetControllerFactory(mvcControllerFactory);
您可以从 asax Application_Start()
参见this answer有关使用 Ninject 和 MVC3 的更多详细信息
关于asp.net-mvc-3 - MVC3 Code First/存储库的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13252851/