3

我在尝试使用 Ninject 的使用 MVC 的沼泽标准三层项目时遇到问题。我有一个 MemberRepository:

public class MemberRepository : IMemberRepository{
     public bool Save(Member member){
          //saves member
     }
}

然后我有我的服务层:

public class MemberService : IMemberService{
     public bool Register(string email){
        //Do Stuff & Populate Member Object
        _repo.Save(member);
     }
}

鉴于我将使用 Ninject,我设置 AccountController 的最佳方式是什么。我是否应该像这样将 MemberService 传递给构造函数:

public class AccountController : Controller
{
    IMemberService _memberService;

    public AccountController(IMemberService memberService)
    {
        _memberService = memberService;
    }
}

或者传入存储库:

public class AccountController : Controller
{
    IMemberService _memberService;

    public AccountController(IMemberRepository memberRepo)
    {
        _memberService = new MemberService(memberRepo);
    }
}

或两者?

我最初只有一个存储库(没有服务层),但我必须实现一个服务层,我不确定在我的 NinjectWebCommon.cs 文件中注册内核时如何处理“依赖关系”。最初只是这样:

    kernel.Bind<IMemberRepository>().To<SqlMemberRepository>();

但现在我想知道是否需要注册 IMemberService 并将 repo 作为某种参数。

:s 感觉有点失落。希望我说得通,有人可以帮忙。

4

1 回答 1

6

I've never used Ninject, I've been using Unity, but the same principles exist so hopefully this might help.

The service layer is the thing that is exposed to the controller - the controller needs to know nothing about the underlying repository. The flow is as follows, and each layer doesn't know about the layers above it:

Controller -> Service > Repository

So I would go with option 1, and then inject the repository into the constructor of the service.

public class MemberService : IMemberService {
     private readonly IMemberRepository _repo;

     [Inject]
     public MemberService (IMemberRepository repo){
        this._repo = repo;
     }

     public bool Register(string email){
        //Do Stuff & Populate Member Object
        _repo.Save(member);
     }
}

and

public class AccountController : Controller
{
    private readonly IMemberService _memberService;

    [Inject]
    public AccountController(IMemberService memberService)
    {
        _memberService = memberService;
    }
}

That example obviously uses constructor injection but you can use property/field injection if you want instead. When you register your dependencies, you'll have to register both:

kernel.Bind<IMemberRepository>().To<SqlMemberRepository>();
kernel.Bind<IMemberService>().To<MemberService>();
于 2012-11-12T13:37:02.063 回答