本篇内容主要讲解“Unity控制反转的方法是什么”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Unity控制反转的方法是什么”吧!
目前累计服务客户近千家,积累了丰富的产品开发及服务经验。以网站设计水平和技术实力,树立企业形象,为客户提供成都网站设计、成都网站制作、网站策划、网页设计、网络营销、VI设计、网站改版、漏洞修补等服务。创新互联始终以务实、诚信为根本,不断创新和提高建站品质,通过对领先技术的掌握、对创意设计的研究、对客户形象的视觉传递、对应用系统的结合,为客户提供更好的一站式互联网解决方案,携手广大客户,共同发展进步。
控制反转上层不依赖下层,而是依赖第三方依赖注入容器
上次的SimpleFactory就可以看做是第三方容器。学生student依赖SimpleFactory 而不直接依赖细节(Honor)
我们常用的第三方容器就是Unity,在VS中通过NuGet引入Unity的Dll,改造我们的Main方法
static void Main(string[] args)
{
{
BasePhone honor = SimpleFactory.CreatePhone();
IPlayPhone student = SimpleFactory.CreateStudent();
student.PlayPhone(honor);
IUnityContainer unityContainer = new UnityContainer();
unityContainer.RegisterType();
var studentUnity = unityContainer.Resolve();
studentUnity.PlayPhone(honor);
//Honor honor = new Honor();
//Student student = new Student();
//student.PlayPhone(honor);
//student.PlayPhone(lumiaPhone);
//student.PlayApplePhone(applePhone);
//student.PlayGalaxy(galaxy);
//student.PlayHonor(honor);
}
Console.ReadKey();
} 再将代码改造下增加IPerson,Iiphone,IGame
public interface IPerson
{
Iiphone Iphone { get; set; }
IGame Game { get; set; }
}
public class Student: BasePerson, IPerson
{
[Dependency]
public Iiphone Iphone { get; set; }
[Dependency]
public IGame Game { get; set; }
}
public class Teacher: BasePerson, IPerson
{
[Dependency]
public Iiphone Iphone { get; set; }
[Dependency]
public IGame Game { get; set; }
} public interface Iiphone
{
void UsePhone();
}
public class Galaxy:BasePhone, Iiphone
{
public override void System()
{
Console.WriteLine("ANDROID");
}
public void UsePhone()
{
Console.WriteLine("Galaxy");
}
} public interface IGame
{
void Game();
}
public class SgsGame:IGame
{
public void Game()
{
Console.WriteLine("play 三国杀Game");
}
}
public class LolGame:IGame
{
public void Game()
{
Console.WriteLine("Play LoLGame");
}
}
static void Main(string[] args)
{
{
IUnityContainer unityContainer = new UnityContainer();
unityContainer.RegisterType();
unityContainer.RegisterType();
unityContainer.RegisterType();
var studentUnity = unityContainer.Resolve();
studentUnity.Iphone.UsePhone();
studentUnity.Game.Game();
} 这里用的是依赖注入中的属性注入,属性注入在构造函数注入之后执行,而且需要增加[Dependency]这个特性,并且需要添加using Microsoft.Practices.Unity;的引用,所以大部分时候都用构造函数注入更方便, 还有方法注入项目中用的很少,在方法上加[InjectionMethod]特性
unity提供更灵活的用配置文件注册的方法 在项目配置文件增加
则Main函数修改
static void Main(string[] args)
{
{
IUnityContainer unityContainer = new UnityContainer();
UnityConfigurationSection configuration = (UnityConfigurationSection)ConfigurationManager.GetSection(UnityConfigurationSection.SectionName);
configuration.Configure(unityContainer, "defaultContainer");
var studentUnity = unityContainer.Resolve();
studentUnity.OutputIdentity();
studentUnity.Iphone.UsePhone();
studentUnity.Game.Game();
}
Console.ReadKey();
} 到此,相信大家对“Unity控制反转的方法是什么”有了更深的了解,不妨来实际操作一番吧!这里是创新互联网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
文章名称:Unity控制反转的方法是什么
文章源于:http://www.jxjierui.cn/article/psgcog.html


咨询
建站咨询
