Ninject,Repository和DAL

时间:2012-04-04 10:01:22

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

我是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();
        }
}

2 个答案:

答案 0 :(得分:1)

您获得nullref是因为您没有设置_userRepository。在AdminController的构造函数中设置它,Niject会愉快地注入它:

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

    //...
}

您可以在此处详细了解injection patterns with Ninjecthow injection works

答案 1 :(得分: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
}