0

I have an ASP.NET MVC 5 website and I would like to access current user info from my own class (that has no idea of http context). How can I inject it into that class?

Apparently, I can't even inject IUser into a MVC controller either. It throws this error.

System.MissingMethodException: No parameterless constructor defined for this object

I don't want to pass the user info manually.

Thanks

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Null Head
  • 2,877
  • 13
  • 61
  • 83

1 Answers1

0

You must create a controller factory like

public class MyControllerFactory : DefaultControllerFactory
{
    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        if (controllerType == null)
            throw new InvalidOperationException(string.Format("Page not found: {0}", requestContext.HttpContext.Request.Url.AbsoluteUri.ToString(CultureInfo.InvariantCulture)));
        return ObjectFactory.GetInstance(controllerType) as Controller;
    }
}

and in golobal.asax in Application_start() add

ObjectFactory.Initialize(x =>
{
x.For<IUserService>().Use<UserService>();
}
ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());

and in your controller

public class UserController:Controller{
public ContractController(IUserService userService){}
}

now IUserService injected in your controller

M.Azad
  • 3,673
  • 8
  • 47
  • 77