就Unity使用有感

使用了Unity有段时间了,但是对其了解不深刻。自己写篇文章来以备后用吧。

创建一个website或者WebApplication

增加Global.asax文件  在Application_Start方法总增加初始化IUnityContainer容器的操作

 

代码
IUnityContainer container = new UnityContainer();
container
.RegisterType
<ImplService, UnityService>();
container
.RegisterInstance(
new ServiceMethod());
WebSingleton.ApplicationContainer
= container;

 

 

注册接口和实现

添加单例

 

代码
public static class WebSingleton
{
public static IUnityContainer ApplicationContainer
{
get
{
return HttpContext.Current.Application["Container"] as IUnityContainer;
}
set
{
HttpContext.Current.Application[
"Container"] = value;
}
}
}

创建页面基类 BasePage

 

代码
public class BasePage : System.Web.UI.Page
{
[Dependency]
public ImplService service { get; set; }
protected override void OnLoad(EventArgs e)
{
WebSingleton.ApplicationContainer.BuildUp(
this);
base.OnLoad(e);

}
}

 

 

将容器 BuildUp 需要注意的是ImplService接口必须加上[Dependency]这样才能实现注入,不然ImplService一直会报空指针异常

接口:

public interface ImplService
{
bool UserLogin(string uname, string password);
}

 

public class ServiceMethod
{
[Dependency]
public AdminService adminService { get; set; }
}

 

 

实现:

代码
public class UnityService : ServiceMethod, ImplService
{
#region ImplService Members

public bool UserLogin(string uname, string password)
{
return this.adminService.UserLogin(uname, password);
}

#endregion
}

 

 

 

public class AdminService
{

public bool UserLogin(string usnme, string password) {
return true;
}
}

 

 

可能设计不是特别合理,只是自己作为使用Microsoft.Practices.Unity后的样例。请指正!谢谢。

下面为源码下载地址:http://www.nvrenlin.com/code/TestUnity.rar 

 女人林这个小站是作者的 也希望大家支持

女人时尚

重庆资讯 

posted @ 2010-12-28 09:20  奇想  阅读(398)  评论(0编辑  收藏  举报