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 to be injected into the controller as follows:

 public class ProfilesController : BaseController { private readonly IUserProfileService m_profileService; public ProfilesController(IUserProfileService profileService) { m_profileService = profileService; } } 

I do not know how I can register this interface and its implementation in the Ninject container to pass the userName parameter when Ninject enters an instance of this service.

Any ideas how I can achieve this?

+4
source share
3 answers

One option is to enter a factory and create your dependency using Create(string userName) .

 public class UserProfileServiceFactory { public IUserProfileService Create(string userName) { return new UserProfileService(userName); } } 

It might seem like you need to create another class, but the benefits mostly arise when UserProfileService accepts additional dependencies.

+3
source

Ninject's technical answer is to use constructor arguments as follows:

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

Of course, you need to find out where Carl is coming from. It really depends on your application. Maybe this is a web application and its on HttpContex? I dont know. If it gets quite complicated, you can write an IProvider rather than perform a regular bind.

+5
source

The trick is not to enter a username in this class. You call this class a service, so it will probably work transparently with multiple users. I see two solutions:

  • Add an abstraction to the service that represents the current user:

     public class UserProfileService : IUserProfileService { private readonly IPrincipal currentUser; public UserProfileService(IPrincipal currentUser) { this.currentUser = currentUser; } void IUserProfileService.SomeOperation() { var user = this.currentUser; // Do some nice stuff with user } } 
  • Create an implementation specific to the technology you are working with, for example:

     public class AspNetUserProfileService : IUserProfileService { public AspNetUserProfileService() { } void IUserProfileService.SomeOperation() { var user = this.CurrentUser; // Do some nice stuff with user } private IPrincipal CurrentUser { get { return HttpContext.Current.User; } } } 

If you can, go with the first option.

+3
source

All Articles