使用ASP.NET MVC 5和Structuremap,Setter Property Injection不能在静态类中工作

时间:2016-04-28 03:14:42

标签: c# asp.net-mvc structuremap

我在库项目中创建了一个静态类Util,用于在项目asp.net mvc 5中定义公共方法,我使用的是structuremap.mvc5,但它没有初始化安装IService是静态属性,我声明在静态类中。谢谢你的帮助:

Config Class Ioc:

public static class IoC {
    public static IContainer Initialize() {
        ObjectFactory.Initialize(x =>
        {
            //Standard registration
            x.For<IStudentRepository>().Use<StudentRepository>();
            x.For<IStudentService>().Use<StudentService>();
            x.For<IApplicationSettings>().Use<WebConfigApplicationSettings>();
            x.For<IAuthProvider>().Use<FormsAuthProvider>();
            //Setter injection
            x.Policies.FillAllPropertiesOfType<IStudentService>().Use<StudentService>();
            x.Policies.SetAllProperties(prop =>
            {
                prop.OfType<IStudentService>();
            });

        });            
        return ObjectFactory.Container;            
    }
}

Class Util:

public static class Util 
{       
    private static IStudentService _studentService;

    public static IQueryable<User> GetAllStudents()
    {
        return _studentService.GetAllStudents();
    }

    public static T ParseEnum<T>(string value)
    {
        return (T)Enum.Parse(typeof(T), value, true);
    }

    public static List<PermissionType> GetAllPermissionByUserID(int userID)
    {
        return _studentService.GetAllPermissionByUserID(userID);
    }

    public static bool IsAuthentication(string user, string password)
    {
        return _studentService.IsAuthentication(user,password);
    }
    public static User FindUserByUsername(string username)
    {
        return _studentService.FindUserByUsername(username);
    }
}

错误页面: enter image description here

1 个答案:

答案 0 :(得分:1)

您没有初始化_studentService,所以您必须这样做。 要创建studentService的新实例,您可以使用ServiceLocator或Property Setter

试试这个:

public static Util 
{
     _studentService=ObjectFactory.Container.GetInstance<StudentService>();
}

对于Setter Injection,您可以使用:

 [SetterProperty]
 public IStudentService StudentService{get;set;}

但我不确定静态类中的setter属性。