Asp.net mvc 3 统一依赖注入和重定向到操作
我在项目中使用Unity DI,但当从一个操作重定向到另一个操作时,会出现以下错误: 没有为此对象定义无参数构造函数。在FirstController中,服务属性初始化正确,并且当直接调用SecondController时,服务属性初始化正确,但是当使用FirstController中的RedictToAction方法重定向到SecondController时,会出现以下错误:没有为此对象定义无参数构造函数。 我的示例代码是:Asp.net mvc 3 统一依赖注入和重定向到操作,asp.net-mvc-3,dependency-injection,Asp.net Mvc 3,Dependency Injection,我在项目中使用Unity DI,但当从一个操作重定向到另一个操作时,会出现以下错误: 没有为此对象定义无参数构造函数。在FirstController中,服务属性初始化正确,并且当直接调用SecondController时,服务属性初始化正确,但是当使用FirstController中的RedictToAction方法重定向到SecondController时,会出现以下错误:没有为此对象定义无参数构造函数。 我的示例代码是: public interface IService { st
public interface IService
{
string Get();
}
public class Service : IService
{
public string Get()
{
return "Data";
}
}
public class FirstController : Controller
{
private readonly IService _service;
public FirstController(IService service)
{
_service = service;
}
public ActionResult Index()
{
return RedirectToAction("Index", "Second"); -----> this line
}
}
public class SecondController : Controller
{
private readonly IService _service;
public SecondController(IService service)
{
_service = service;
}
public ActionResult Index()
{
return View();
}
}
DI代码:
public static class Bootstrapper
{
public static IUnityContainer Initialise()
{
var container = BuildUnityContainer();
System.Web.Mvc.DependencyResolver.SetResolver(new DependencyResolver(container));
return container;
}
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
container.RegisterType<IService, Service>();
return container;
}
}
public class DependencyResolver : IDependencyResolver
{
private readonly IUnityContainer _unityContainer;
public DependencyResolver(IUnityContainer unityContainer)
{
_unityContainer = unityContainer;
}
public object GetService(System.Type serviceType)
{
try
{
var service = _unityContainer.Resolve(serviceType);
return service;
}
catch (Exception ex)
{
return null;
}
}
public IEnumerable<object> GetServices(System.Type serviceType)
{
try
{
return _unityContainer.ResolveAll(serviceType);
}
catch
{
return new List<object>();
}
}
}
演示如何配置Unity。SecondController中索引操作的ViewModel是什么?也许这是同一个问题?
Bootstrapper.Initialise();