Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ninject constructor argument

I have this interface:

public interface IUserProfileService
{
    // stuff
}

Implemented by:

public class UserProfileService : IUserProfileService
{
    private readonly string m_userName;

    public UserProfileService(string userName)
    {
        m_userName = userName;
    }
}

I need this injected into a controller like this:

public class ProfilesController : BaseController
{
    private readonly IUserProfileService m_profileService;

    public ProfilesController(IUserProfileService profileService)
    {
        m_profileService = profileService;
    }
}

I don't know how I can register this interface and its implementation into Ninject container so that userName param is passed in when the Ninject inits an instance of this service.

Any ideas how I can achieve this?

like image 708
kind_robot Avatar asked Dec 21 '22 12:12

kind_robot


1 Answers

The technical ninject answer is to use constructor arguments like so:

Bind<IUserProfileService>().To<UserProfileService>().WithConstructorArgument("userName", "karl");

Of course you need to figure out where "karl" comes from. It really depends on your app. Maybe its a web app and it's on the HttpContex? I don't know. If it gets rather complicated then you might want to write a IProvider rather than doing a regular binding.

like image 179
ryber Avatar answered Jan 01 '23 00:01

ryber