2012-05-16 30 views
1

我有很多服務,每個服務都有一些功能。幾乎每個功能都需要一個當前用戶需要執行的「角色」。使用需要角色在服務內權限的功能

有沒有比在每個方法的開頭放置下面的代碼更好的方法?如果我可以用Attributes來裝飾這些方法,那將會很整潔,但我不確定如何在這裏應用它們。

public void CreateTruck(TruckDto dto) 
{ 
    var currentUser = GetCurrentUser(); 
    if (!currentUser.Can("CreateTruck")) 
     throw PermissionException("..."); 

    // otherwise proceed normally 
} 
+0

如果只有可能通過使用屬性注入代碼... – zmbq

回答

0

有兩種方法我看到這種情況出現:

1 - 你不改變任何事情,或者僅僅作出這樣的一個簡單的一個班輪:

EnsureUserCan("CreateTruck"); 

內部具有這種方法撥打:

protected void EnsureUserCan(string role) 
{ 
    if(!GetCurrentUser().Can(role)) 
     throw PermissionException("..."); 
} 

2 - 你移動到一個調用模式:

var myNewTruck = ServiceInvoker.Invoke<TruckService>(x => x.CreateTruck(dto)); 

public class ServiceInvoker 
{ 
    public ReturnType Invoke<ServiceType, ReturnType>(Expression<Func<ServiceType, ReturnType>> methodExpression) 
    { 
     // blah blah 
     var myService = IoC.Resolve<ServiceType>(); 

     return methodExpression.Compile()(myService); // etc 
    } 
} 

而您的invoke方法檢查屬性的表達式,因此可以基於屬性拋出異常。這似乎是過度殺傷。

相關問題