2016-04-28 11 views
0

我在庫項目中創建一個靜態類Util用於定義項目asp.net mvc 5中的常用方法,我使用了structuremap.mvc5 ,但它不初始化IService的安裝是靜態屬性,我聲明在靜態類。謝謝你的幫助:Setter屬性注入在靜態類中不起作用,使用ASP.NET MVC 5和Structuremap

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

類的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

+0

爲什麼你設置類Util是靜態的? –

+0

@Linh Tuan:因爲我在解決方案的任何地方調用了類Util,並且不從類中初始化對象。 –

+0

此問題「_studentService」未初始化 –

回答

1

你是不是初始化_studentService,所以你必須做到這一點。 用於創建studentService的新實例,您可以使用服務定位器或屬性setter

試試這個:

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

和Setter注入你使用這樣的:

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

,但我不知道靜態類中的setter屬性。

相關問題