Ninject nested constructor argument

93 Views Asked by At

the way im binding my services with nested constructors is working but it seems like there's a better way to inject these nested constructors. Please tell me what is the proper way to do it for this kind of scenario, also if there is something wrong with the way I layer my application kindly point it out also thank you!

Please check the codes below:

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))
        );
    }

EDIT: after several tries I found another way to achieve my goal which i think is much cleaner(note: I dont know how it automatically find the MyContext parameter of AuthorRepository but it does)

2nd Way:

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<IAuthorService>().To<AuthorService>();
    kernel.Bind<IAuthorRepository>().To<AuthorRepository>();
}
0

There are 0 best solutions below