繁体   English   中英

使用ASP.NET MVC 5和Structuremap,Setter属性注入在静态类中不起作用

[英]Setter Property Injection don't work in static class, using ASP.NET MVC 5 and Structuremap

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

配置类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;            
    }
}

类实用程序:

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

错误页面: 在此处输入图片说明

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

尝试这个:

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

对于Setter注入,请使用以下命令:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM