System.web.Mvc DependencyResolver无法为泛型类创建对象

时间:2014-06-20 13:28:50

标签: c# asp.net-mvc-3 dependency-injection dependency-resolver

我正在尝试在Controller中使用dependencyinjection并使用 System.Web.MvcDependencyResolver.Current.GetService(),用于在控制器类中创建服务实例。

当服务接口非通用时,这可以正常工作,如下所示

public interface IProfileManagementService
{
   IList<News> GetSavedSearchList(int userObjectId, ApplicationType applicationType,int? vendorUserObjectId);
}

我的依赖解析器语法如下所示为我提供了 ProfileManagementService

的实例
DependencyResolver.Current.GetService<IProfileManagementService>();

但如果我创建如下的任何通用服务接口,

public interface ICommonProfileManagementService<T>
{
   IList<T> GetSavedSearchList(int userObjectId, ApplicationType applicationType,int? vendorUserObjectId);
}

但我得到一个null( CommonProfileManagementService 对象没有为下面的代码创建)

DependencyResolver.Current.GetService<ICommonProfileManagementService<News>>();

请建议一些传递方式

IService<T>

而不是

IService

到DependencyResolver.Current.GetService()

1 个答案:

答案 0 :(得分:3)

以下是完整代码,包括从DependencyResolver返回泛型所需的语法。

using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Microsoft.Practices.Unity.Mvc;

namespace ConsoleApplication2
{
    class Program
    {
        public interface IService<T>
        {
            List<T> GetService();
        }

        public class Service<T> : IService<T>
        {
            public List<T> GetService()
            {
                return new List<T>();
            }
        }

        static void Main(string[] args)
        {
            var container = new UnityContainer();

            container.RegisterType(typeof(IService<>), typeof(Service<>));

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));

            var service = DependencyResolver.Current.GetService(typeof(IService<string>));

            Console.WriteLine(service.ToString());

            Console.ReadKey();
        }
    }
}