0

我有一个 ASP.NET MVC 5 网站,我想从我自己的类(不知道 http 上下文)访问当前用户信息。我怎样才能将它注入那个类?

显然,我什至不能注入IUserMVC 控制器。它抛出这个错误。

System.MissingMethodException:没有为此对象定义无参数构造函数

我不想手动传递用户信息。

谢谢

4

1 回答 1

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

于 2015-03-08T09:48:16.690 回答