Service描述和實例
在系統開發中會涉及很多不同的服務,所謂的服務就是把邏輯進行封裝後的業務模塊,包括權限服務,信息服務,事件服務,狀態持久性服務,業務自定義功能等方面的服務,所有這些服務有些是系統已經定義好基本接口的,有些卻需要自行定義好接口,開發完這些服務以後可以通過SCSF提供IOC容器來進行加載並使用。
1. 創建Module項目:
圖2.9.1
2. 在Infrastructure.Interface項目中增加兩個接口IroleData,IloginService,並輸入如下代碼:
public interface IRoleData {
string RoleName{get;set;}
string[] Description { get;set;}
} public interface ILoginService { IRoleData getRole(); } |
添加兩個類:RoleData,LoginService,分別繼承並實現該兩個接口;
public class RoleData :IRoleData { private string _rolename; private string[] _description; #region IRoleData 成員 public string[] Description { get { return _description; } set { this._description = value; } } public string RoleName { get { return _rolename; } set { _rolename = value; } } #endregion } public class LoginService:ILoginService { #region ILoginService 成員 public IRoleData getRole() { LoginFrm login = new LoginFrm(); login.ShowDialog(); return login.RoleInfo(); } #endregion } |
在類SmartClientApplication中把對應的服務添加進去,以便能在系統啓動時可以把對應的服務注入到容器中;
protected override void AddServices() { 。。。 //增加登陸界面的服務 RootWorkItem.Services.AddNew<LoginService, ILoginService>(); RootWorkItem.Services.AddNew<RoleData, IRoleData>(); RootWorkItem.Services.Remove<IAuthenticationService>(); RootWorkItem.Services.AddNew<SimpleLoginAuthenticationService, IAuthenticationService>(); } |
由於涉及權限控制,於是創建類SimpleLoginAuthenticationService並實現系統提供的接口IauthenticationService;
public class SimpleLoginAuthenticationService : IAuthenticationService { private ILoginService _login; [InjectionConstructor] public SimpleLoginAuthenticationService([ServiceDependency] ILoginService login) { _login = login; }
#region IAuthenticationService 成員
public void Authenticate() { IRoleData user=_login.getRole(); if (user != null) { GenericIdentity identity = new GenericIdentity(user.RoleName); GenericPrincipal principal = new GenericPrincipal(identity, user.Description); Thread.CurrentPrincipal = principal; } else { throw new AuthenticationException(Resources.NoUserProvidedForAuthentication); }
}
#endregion } |
其中方法Authenticate的作用就是把角色狀態注入系統中並讓後邊啓動的系統模塊能使用。
3. 創建登陸界面;
圖2.9.2
添加以下代碼:
public partial class LoginFrm : Form { public LoginFrm() { InitializeComponent(); }
private RoleData _roledata;
public RoleData RoleInfo() { return _roledata; }
private void btnOk_Click(object sender, EventArgs e) { RoleData rd = new RoleData(); if (this.rbtnMain.Checked) { rd.RoleName = "Main"; rd.Description = new string[] { "this is Main region" }; this._roledata = rd; } if (this.rbtnLeft.Checked) { rd.RoleName = "Left"; rd.Description = new string[] { "this is Left region" }; this._roledata = rd; } if (this.rBtnOther.Checked) { rd.RoleName = "Other"; rd.Description = new string[] { "this is Other region" }; this._roledata = rd; } this.Close(); }
private void btnCancel_Click(object sender, EventArgs e) { this.Close(); }
} |
4. 運行程序選擇MainRole權限後等到相應的信息;
圖2.9.3