Unity 配置文件 基本设置

本文详细介绍了在应用程序中使用Unity容器进行依赖注入的方法,包括配置文件app.config的使用,以及如何在不同场景下注册并使用接口实例。通过实例展示了如何在Common程序集中定义接口,并在ValueProviders程序集中实现接口的具体行为,最终通过Unity容器加载配置并实例化接口,实现灵活且高效的应用程序组件管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

配置文件app.config,其中的<configSections>配置节内的信息是必加的,不然载入会出错

View Code
<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <alias alias="IValueProvider" type="Common.IValueProvider,Common"/>
    <container name="ValueProviders">
      <register type="IValueProvider" name="Memery" mapTo="ValueProviders.MemeryProvider,ValueProviders"/>
      <register type="IValueProvider" name="Viedo" mapTo="ValueProviders.VideoCardProvider,ValueProviders"/>
      <register type="IValueProvider" name="Date" mapTo="ValueProviders.DateProvider,ValueProviders"/>
      <register type="IValueProvider" name="Name" mapTo="ValueProviders.NameProvider,ValueProviders"/>
    </container>
  </unity>
  <startup>
    <supportedRuntime version="v2.0.50727"/>
  </startup>
</configuration>

在Common程序集中的接口:

    public interface IValueProvider
    {
        string GetValue(object key);
    }

在ValueProviders程序集中的其中一个接口实例:

    public  class DateProvider:IValueProvider
    {
        public string GetValue(object key)
        {
            return DateTime.Now.ToShortDateString();
        }
    }

调用方法:

            UnityContainer container = new UnityContainer();
            container.LoadConfiguration("ValueProviders");
            var provider= container.Resolve<Common.IValueProvider>("Viedo");
            provider.GetValue(null);

如果不带参数,直接LoadConfiguration,会载入名称为”“或者没有name属性的container配置节,如果都没有会报错

转载于:https://www.cnblogs.com/FlyCat/archive/2012/09/26/2703997.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值