统一依赖注入和重定向到操作

时间:2014-04-07 06:52:16

标签: asp.net-mvc-3 dependency-injection

我在项目中使用Unity DI,但是当从一个动作重定向到另一个动作时会出现此错误: 没有为此对象定义的无参数构造函数。在FirstController _service属性初始化正确,并且当调用SecondController直接_service属性初始化正确时,但是当使用FirstController的RedirctToAction方法重定向到SecondController时得到此错误:没有为此对象定义无参数构造函数。 我的示例代码是:

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>();
        }
    }
}

Application_Start初始化:

Bootstrapper.Initialise();

0 个答案:

没有答案