分享

就Unity使用有感

 贾朋亮博客 2013-03-16

使用了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./code/TestUnity.rar 

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

女人时尚

重庆资讯 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多