MVC 3 + IoC + NInject +存储库+ LINQ [英] MVC 3 + IoC + NInject + Repositories + LINQ

查看:52
本文介绍了MVC 3 + IoC + NInject +存储库+ LINQ的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的MVC 3应用程序中使用NInject,但我有一个问题.

I'm trying to work with NInject in my MVC 3 application, and i have one question.

接口

public interface ITalesRepository
{
    IEnumerable<Tale> GetAllTales();
}

存储库

public class TalesRepository : ITalesRepository
{
    private FairyTalesMVC3DataContext _dataContext;

    public TalesRepository(FairyTalesMVC3DataContext dataContext)
    {
        _dataContext = dataContext;
    }

    public IEnumerable<Tale> GetAllTales()
    {
        return _dataContext.Tales.OrderBy(c => c.NameAn);
    }
}

家庭控制器

public class HomeController : Controller
{
    private readonly ITalesRepository _talesRepository;

    public HomeController(ITalesRepository talesRepository)
    {
        _talesRepository = talesRepository;
    }

    public ActionResult Index()
    {
        ViewBag.Tales = _talesRepository.GetAllTales();

        return View();
    }
}

因此,我需要使用DataContext初始化TalesRepository,现在是这样的:

So, i need to initialize my TalesRepository with DataContext, and now it is so:

private void RegisterDependencyResolver()
{
    var kernel = new StandardKernel();
    kernel.Bind<ITalesRepository>().To<TalesRepository>().WithConstructorArgument("dataContext", new FairyTalesMVC3DataContext(ConfigurationManager.ConnectionStrings["dbFairyTalesConnectionString"].ConnectionString));
    DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
}

所以,我的问题是,还好吗?

So, my question, is it ok or something wrong?

推荐答案

首先:

public IEnumerable<Tale> GetAllTales()
{
    return _dataContext.Tales.OrderBy(c => c.NameAn);
}

我将.ToList()添加到末尾.否则,您将在表示层中遇到数据层异常,这是不对的.

I would add .ToList() to the end. Else you'll get data layer exceptions in your presentation layer which is not fine.

接下来,我建议您切换到ViewModels,而不要使用ViewBag.如果使用ViewModels,防止逻辑泄漏到视图中要容易得多.因为您可以将逻辑添加到ViewModel,从而使用该模型在所有视图中获得相同的行为.

Next, I would recommend that you switch to ViewModels instead of using ViewBag. It's a lot easier to prevent that logic leaks into the views if you are using ViewModels. Since you can add the logic to the ViewModel and thus get the same behaviour in all views using the model.

这篇关于MVC 3 + IoC + NInject +存储库+ LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆