@(编程)
1. 通过Nuget下载Unity
这个就不介绍了
2. 接口代码
namespace UnityDemo
{
interface ILogIn
{
void Login();
}
}
namespace UnityDemo
{
interface IUser
{
string GetUserName();
}
}
3. 实现代码
using Microsoft.Practices.Unity;
using System;
namespace UnityDemo
{
class LogInImpl : ILogIn
{
[Dependency]
public IUser userOper { get; set; }
public void Login()
{
Console.WriteLine(this.userOper.GetUserName());
}
}
}
namespace UnityDemo
{
class UserImpl:IUser
{
public string GetUserName()
{
return "keke";
}
}
}
4. 配置文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration"/>
</configSections>
<unity>
<containers>
<container name="defaultContainer">
<register type="UnityDemo.ILogIn,UnityDemo" mapTo="UnityDemo.LogInImpl,UnityDemo" />
<register type="UnityDemo.IUser,UnityDemo" mapTo="UnityDemo.UserImpl,UnityDemo" />
</container>
</containers>
</unity>
</configuration>
5. 调用代码
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System;
using System.Configuration;
namespace UnityDemo
{
class Program
{
static void Main(string[] args)
{
IUnityContainer container = new UnityContainer();
UnityConfigurationSection configuration = ConfigurationManager.GetSection(UnityConfigurationSection.SectionName)
as UnityConfigurationSection;
configuration.Configure(container, "defaultContainer");
var item = container.Resolve<ILogIn>();
item.Login();
Console.Read();
}
}
}
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/20962.html