0

我是 MVC、存储库概念和依赖注入的新手。

我的存储库和 DAL 看起来像

public interface IRepository<TEntity> where TEntity : class
{
    List<TEntity> FetchAll();
    IQueryable<TEntity> Query { get; }
    void Add(TEntity entity);
    void Delete(TEntity entity);
    void Save();
}


public class Repository<T> : IRepository<T> where T : class
{
    private readonly DataContext _db;

    public Repository(DataContext db)
    {
        _db = db;
    }

    #region IRepository<T> Members

    public IQueryable<T> Query
    {
        get { return _db.GetTable<T>(); }
    }

    public List<T> FetchAll()
    {
        return Query.ToList();
    }

    public void Add(T entity)
    {
        _db.GetTable<T>().InsertOnSubmit(entity);
    }

    public void Delete(T entity)
    {
        _db.GetTable<T>().DeleteOnSubmit(entity);
    }

    public void Save()
    {
        _db.SubmitChanges();
    }

    #endregion
}

在 Global.asax 文件中我有

    private void RegisterDependencyResolver()
    {
        var kernel = new StandardKernel();
        kernel.
            Bind(typeof(IRepository<>)).
            To(typeof(Repository<>))
            .WithConstructorArgument("db", new DataContext(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()));
        DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
    }

但是当我尝试访问存储库时,我得到“ Object reference not set to an instance of an object”。我是否正确理解存储库和注入应该如何工作?

 public class AdminController : Controller
    {

       private readonly IRepository<User> _userRepository;

        public ActionResult Index()
        {
            var a = _userRepository.FetchAll(); //I get exception here
            return View();
        }
}
4

2 回答 2

1

你得到 nullref 因为你没有设置_userRepository. 在 s 构造函数中设置它,AdminControllerNiject 会愉快地注入它:

public class AdminController : Controller
{
    private readonly IRepository<User> _userRepository;
    public AdminController(IRepository<User> userRepository)
    {
        _userRepository = userRepository;
    }

    //...
}

你可以在这里阅读更多关于Ninject 的注入模式以及注入是如何工作的。

于 2012-04-04T10:05:35.017 回答
0

在网络配置文件中

<appSettings>
    <add key="RepoSetting" value="Solution.DAL.OrderRepository"/>
</appSettings>

ninject web 常用类中

private static void RegisterServices(Ikernel Kernel)
{
    //kernl.Bind<Irepo>().To<CustRepo>();

    string name = WebConfigurationManager.AppSettings["RepoSetting"];
    Type repoToInject = Assembly.GetExecutingAssembly().GetType(name);

    kernel.Bind<ICustomerRepository>().To(repoToInject
}
于 2016-08-26T10:32:09.907 回答