请有人帮助我,因为我感到困惑。
我有一个像这样的实体:
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; }
}
如果我这样声明我的控制器:
public class SearchController : Controller
{
private ICodeRepository cRepo;
public SearchController(ICodeRepository codeRepository)
{
cRepo = codeRepository;
}
}
然后尝试cRepo.GetCodeById(1)
没有任何反应。但是如果我声明私有ICodeRepository rep = new SQLCodeRepository
然后调用rep.GetCodeById(1)
我可以看到被调用的存储库中的方法。
我做错了什么?
答案 0 :(得分:3)
从构造函数签名看起来,您将要进行一些依赖注入。您缺少的步骤是使用Castle Windsor之类的工具设置DI容器。然后,配置MVC解析程序以使用DI容器为您提供ICodeRepository
的正确实现。
请参阅this
您需要创建一个实现IDependencyResolver
和IDependencyScope
的解析程序以及一个继承DefaultControllerFactory
的控制器工厂
一旦你有了这些,你可以做以下事情:
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()
有关使用Ninject和MVC3的详细信息,请参阅this answer