有没有办法向构造函数注入一个参数,该参数当前是在basecontroller的Initialize方法中创建的?
示例代码:
public class SSBaseController : Controller
{
protected UserProfileClass UserProfile;
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
UserProfile = UserProfileGetter.getProfileFromDB();
}
}
public class SSController:SSBaseController
{
private IProcessService processService;
public SSController(IProcessService _processService)
{
processService = _processService;
}
}
public interface IProcessService
{
void doStuff();
}
public class ProcessService1 : IProcessService
{
private UserProfileClass upc;
private string _name;
public ProcessService1(UserProfileClass _profileClass)
{
upc = _profileClass;
}
public void doStuff()
{
_name = upc.name;
upc.name = "xxx";
}
}
public class UserProfileGetter
{
public static UserProfileClass getProfileFromDB()
{
return null;
}
}
public class UserProfileClass
{
public string name;
}
另外我想摆脱初始化,这可能吗? 如何在SSController中使用该参数注册ProcessService而不是null?
答案 0 :(得分:0)
可以集成ASP.NET MVC和Autofaq。您需要做的唯一两件事是注册接口实现并指定Controller的构造函数参数。框架将完成所有其余的工作。 见https://code.google.com/p/autofac/wiki/MvcIntegration 这是另外一篇文章:http://blogs.msdn.com/b/roncain/archive/2012/07/16/dependency-injection-with-asp-net-web-api-and-autofac.aspx