asp.net-mvc-3 - MVC3 Code First/存储库的困惑

标签 asp.net-mvc-3 dependency-injection ninject

请有人帮助我,因为我很困惑。

我有一个这样的实体:

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

您需要创建一个实现 IDependencyResolverIDependencyScope 的解析器以及一个继承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/

相关文章:

asp.net-mvc-3 - 使用 AutoMapper 将元数据传输到 View 模型的技术

c# - 使用简单的注入(inject)器基于调用链动态注入(inject)依赖

c# - Ninject 基于字符串的绑定(bind)

asp.net-mvc - asp.net mvc 3 中的错误处理

c# - 在两个服务中使用 ninject 都会在 C# 中创建循环依赖

c# - Asp MVC 4 创建类似于 Html.BeginForm 的自定义 html 帮助器方法

c# - 如何在使用 Razor 将文件上传到 MVC 3 中的 App_Data/Uploads 后查看文件?

asp.net-mvc-3 - 如何在 Orchard 的替代 View 中包含模块资源?

.net - WCF 服务中的依赖注入(inject)

python - 如何模拟用 Python 编写的 Azure 函数中使用的对象