将我的服务与嵌套构造函数绑定的方式正在起作用,但是似乎有更好的方法来注入这些嵌套构造函数。 请告诉我在这种情况下执行此操作的正确方法是什么,如果我对我的应用程序进行分层的方式存在问题,请指出来!
请检查以下代码:
AuthorController.cs
public class AuthorsController : Controller
{
IAuthorService authorService;
public AuthorsController(IAuthorService _authorService)
{
authorService = _authorService;
}
}
AuthorService.cs
public class AuthorService :IAuthorService
{
IAuthorRepository repo = null;
public AuthorService(IAuthorRepository _authorRepository)
{
repo = _authorRepository;
}
}
AuthorRepository
public class AuthorRepository : IAuthorRepository
{
MyContext Context = null;
public AuthorRepository(MyContext _context)
{
Context = _context;
}
}
NinjectWebCommon.cs
private static void RegisterServices(IKernel kernel)
{
MyContext db = new MyContext();
//this is where i have my doubts
kernel.Bind<IAuthorService>().ToConstructor(x =>
new AuthorService(new AuthorRepository(db))
);
}
编辑:经过几次尝试,我发现了另一种实现目标的方法,我认为它更干净(注意:我不知道它是如何自动找到AuthorRepository的MyContext参数的,但是确实如此)>
第二种方式:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IAuthorService>().To<AuthorService>();
kernel.Bind<IAuthorRepository>().To<AuthorRepository>();
}