<转>Unity中Web.Config文件的配置与调用

本文详细解析了Unity配置文件的格式及使用方法,包括配置文件结构、容器配置方式与对象实例生成等核心内容,并提供了实例说明。

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

在本文中,将研究Unity 配置文件的格式、配置的读取、通过示例说明实例的获取。
1. Unity 配置文件的完整格式

ExpandedBlockStart.gif Unty Config
 1  <? xml version="1.0" encoding="utf-8"  ?>  
 2  < configuration >
 3  < configSections >
 4  < section  name ="unity"  type ="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration, Version=1.0.0.0,Culture=neutral, PublicKeyToken=31bf3856ad364e35"   />
 5  </ configSections >
 6 
 7  < unity >
 8  < typeAliases >
 9       < typeAlias  alias ="singleton"  type ="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,Microsoft.Practices.Unity"   />
10       < typeAlias  alias ="external"  type ="Microsoft.Practices.Unity.ExternallyControlledLifetimeManager, Microsoft.Practices.Unity"   />
11       < typeAlias  alias ="IMyInterface"  type ="MyApplication.MyTypes.MyInterface, MyApplication.MyTypes"   />
12       < typeAlias  alias ="MyRealObject"  type ="MyApplication.MyTypes.MyRealObject, MyApplication.MyTypes"   />
13       < typeAlias  alias ="IMyService"  type ="MyApplication.MyTypes.MyService, MyApplication.MyTypes"   />
14       < typeAlias  alias ="MyDataService"  type ="MyApplication.MyTypes.MyDataService, MyApplication.MyTypes"   />
15       < typeAlias  alias ="MyCustomLifetime"  type ="MyApplication.MyLifetimeManager, MyApplication.MyTypes"   />
16  </ typeAliases >
17 
18  < containers >
19       < container  name ="containerOne" >
20         < types >
21           < type  type ="Custom.MyBaseClass"  mapTo ="Custom.MyConcreteClass"   />
22           < type  type ="IMyInterface"  mapTo ="MyRealObject"  name ="MyMapping"   />
23           < type  type ="Custom.MyBaseClass"  mapTo ="Custom.MyConcreteClass" >
24             < lifetime  type ="singleton"   />  
25           </ type >
26           < type  type ="IMyInterface"  mapTo ="MyRealObject"  name ="RealObject" >
27             < lifetime  type ="external"   />
28           </ type >
29           < type  type ="Custom.MyBaseClass"  mapTo ="Custom.MyConcreteClass" >
30             < lifetime  value ="sessionKey"  type ="MyApplication.MyTypes.MyLifetimeManager,MyApplication.MyTypes"   />
31           </ type >
32           < type  type ="IMyInterface"  mapTo ="MyRealObject"  name ="CustomSession" >
33             < lifetime  type ="MyCustomLifetime"  value ="ReverseKey"  typeConverter ="MyApplication.MyTypes.MyTypeConverter,MyApplication.MyTypes"   />
34           </ type >
35           < type  type ="IMyService"  mapTo ="MyDataService"  name ="DataService" >
36             < typeConfig  extensionType ="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration" >
37               < constructor >
38                 < param  name ="connectionString"  parameterType ="string" >
39                   < value  value ="AdventureWorks" />
40                 </ param >
41                 < param  name ="logger"  parameterType ="ILogger" >
42                   < dependency  />
43                 </ param >     (车延禄)
44               </ constructor >  
45               < property  name ="Logger"  propertyType ="ILogger"   />
46               < method  name ="Initialize" >
47                 < param  name ="connectionString"  parameterType ="string" >
48                   < value  value ="contoso" />
49                 </ param >
50                 < param  name ="dataService"  parameterType ="IMyService" >
51                   < dependency  />
52                 </ param >
53               </ method >
54             </ typeConfig >
55           </ type >
56         </ types >
57 
58         < instances >
59           < add  name ="MyInstance1"  type ="System.String"  value ="Some value"   />
60           < add  name ="MyInstance2"  type ="System.DateTime"  value ="2008-02-05T17:50:00"   />
61         </ instances >
62 
63         < extensions >
64           < add  type ="MyApp.MyExtensions.SpecialOne"   />
65         </ extensions >
66 
67         < extensionConfig >
68           < add  name ="MyExtensionConfigHandler"  type ="MyApp.MyExtensions.SpecialOne.ConfigHandler"   />
69         </ extensionConfig >
70       </ container >
71  </ containers >
72  </ unity >
73  </ configuration >
74 
75 

 

结构图示:


看到上面的内容好多人会感到怎么这么复杂啊?实际上,上面的内容是一个完整的结构,以供参考,在日常开发中一般不会全用到的,这里用的最多的元素标记是:<containers>中的<container>内部的<type>标记。

Unity的配置节的名称为”Unity",节处理程序的类型为 Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,它包含在程序集 Microsoft.Practices.Unity.Configuration 中。所在应当在网站是添加该程序集的引用。

unity 的子元素包含了一个 containers 元素,containers 元素可以包含若干个 container 元素。container 元素就是每个容器的配置,它有一个可选的 name 属性,用于指定容器的名称。

<types> 元素是 container 元素的子元素之一。包含任意数量的 type元素,用以添加类型注册,这些配置被container.RegisterType<TFrom,TTo>()注册;
type元素的属性。
name:在注册此类型时使用的名称。此属性是可选的,如果不指定此属性,所在的 add 元素即为默认的类型映射。
type:容器中配置的源类型。如果这是映射注册,这就是映射的起始对象的类型;如果这是单件注册,这就是对象的类型。此属性是必须的。
mapTo:类型映射的目标类型。如果这是映射注册,这就是映射的目标对象的类型。此属性是可选的。
lifetime:设置用于给定的类型和名称的生命周期。是一个来自 LifetimeStyle 枚举的值。有效的值是 Transient(默认),它导致了容器每次都创建一个新的实例;以及 Singleton,它使容器为每个请求返回同一实例。如果在配置一个单件时同时指定了 type 和 mapto 属性,SetSingleton 方法将返回指定在 mapTo 属性中的类型。如果 mapTo 属性没有指定值,SetSingleton 方法将返回指定在 type 属性中的类型。

<instances> 元素保持了用于此容器的已有对象实例的列表。这些对象被用容器的 RegisterInstance 方法进行注册。instances 元素包含了一系列添加单个实例的 add 元素。
add 元素的属性。
name:注册此实例时使用的名称。此属性是可选的。
type:此实例的类型。此属性是可选的。如果忽略,假定的类型是 System.String。
value:用于初始化实例的值。此属性是必须的。
typeConverter:用以转换提供的值到实例的匹配类型的类型转换器。如果没有指定,将使用指定类型的默认转换器。此属性是可选的。

<typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement,Microsoft.Practices.Unity.Configuration">
用来配置在类型注册时,构造函数依赖注入,属性依赖注入和方法依赖注入时的对象初始化信息。
它包含以下几个子元素:
<constructor>
    <param name="connectionString" parameterType="string">
        <value value="AdventureWorks"/>
    </param>
    <param name="logger" parameterType="ILogger">
        <dependency />
    </param>
</constructor>
<property name="Logger" propertyType="ILogger" />
<method name="Initialize">
    <param name="connectionString" parameterType="string">
        <value value="contoso"/>
    </param>
    <param name="dataService" parameterType="IMyService">
        <dependency />
    </param>
</method>
在执行Container.Resolve()生成对象实例的时候,会根据上面的配置信息的内容对要生成的对象进行依赖注入。

二、加载配置信息到容器中
1、加载一个单独的未命名容器或规定了默认容器:
IUnityContainer container = new UnityContainer();
UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
section.Containers.Default.Configure(container);

这样就会根据配置文件中的配置信息,在UnityContainer容器中注册类型映射

2、加载一个特殊命名容器的配置信息,需要使用定义在配置文件中的容器名,而不是引用默认容器。例如,如果在配置中有一个命名为containerOne的容器,能使用如下代码初始化并加载它:
IUnityContainer container = new UnityContainer();
UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
section.Containers["containerOne"].Configure(container);

3、为了从配置信息中创建一个嵌套容器继承, 可以简单的使用CreateChildContainer方法在你需要的继承深度中创建容器对象,然后通过读取各自的配置文件加载合适的配置。下面的代码展示了如何从配置文件中实例化和加载两个容器,这个配置文件同时包含了针对两个命名为containerOne和newstedChildContainer容器的注册信息,类型映射和扩展定义。
IUnityContainer parentContainer = new UnityContainer();
IUnityContainer childContainer = parentContainer.CreateChildContainer();
UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
section.Containers["containerOne"].GetConfigCommand().Configure(parentContainer);
section.Containers["nestedChildContainer"].Configure(childContainer);

三、从容器的映射信息生成对象实例:
这里依然还是用UnityContainer类的Resolve方法来实现的。在此不多说了。

四、一个简单的例子:
1、类的结构:
   

2、Web.Config文件的配置

ExpandedBlockStart.gif WebConfig
 1       < configSections >
 2        < section  name ="unity"  type ="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration" />
 3       </ configSections >
 4       < unity >
 5        < containers >
 6         < container >
 7          < types >
 8           < type  type ="Player,App_Code"  mapTo ="MP3Player,App_Code" ></ type >
 9          </ types >
10         </ container >
11        </ containers >
12       </ unity >

 


    (车延禄)
3、客户代码的实现:
  

ExpandedBlockStart.gif 代码
1    IUnityContainer container  =   new  UnityContainer();
2      UnityConfigurationSection section  =  (UnityConfigurationSection)ConfigurationManager.GetSection( " unity " );
3      section.Containers.Default.Configure(container);
4 
5      Player p  =  container.Resolve < Player > ();
6      Response.Write(p.Play());
7 

 

   
4、运行结果:

转载于:https://www.cnblogs.com/fei-time/archive/2010/02/08/1665704.html

/* * Tencent is pleased to support the open source community by making xLua available. * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System.Collections.Generic; using System; using UnityEngine; using XLua; //配置的详细介绍请看Doc下《XLua的配置.doc》 public static class ExampleGenConfig { //lua中要使用到C#库的配置,比如C#标准库,或者Unity API,第三方库等。 [LuaCallCSharp] public static List<Type> LuaCallCSharp = new List<Type>() { typeof(System.Object), typeof(UnityEngine.Object), typeof(Vector2), typeof(Vector3), typeof(Vector4), typeof(Quaternion), typeof(Color), typeof(Ray), typeof(Bounds), typeof(Ray2D), typeof(Time), typeof(GameObject), typeof(Component), typeof(Behaviour), typeof(Transform), typeof(Resources), typeof(TextAsset), typeof(Keyframe), typeof(AnimationCurve), typeof(AnimationClip), typeof(Animation), typeof(Animator), typeof(MonoBehaviour), typeof(ParticleSystem), typeof(SkinnedMeshRenderer), typeof(Renderer), typeof(WWW), typeof(System.Collections.Generic.List<int>), typeof(Action<string>), typeof(UnityEngine.Debug), typeof(BoxCollider), typeof(Mathf), typeof(UnityEngine.Random), //typeof(Input), typeof(Screen), typeof(Shader), typeof(Material), typeof(SpriteRenderer), }; //C#静态调用Lua的配置(包括事件的原型),仅可以配delegate,interface [CSharpCallLua] public static List<Type> CSharpCallLua = new List<Type>() { typeof(Action), typeof(Func<double, double, double>), typeof(Action<string>), typeof(Action<double>), typeof(UnityEngine.Events.UnityAction), }; //黑名单 [BlackList] public static List<List<string>> BlackList = new List<List<string>>() { new List<string>(){"UnityEngine.WWW", "movie"}, new List<string>(){ "UnityEngine.MonoBehaviour", "runInEditMode"}, new List<string>(){ "UnityEngine.MonoBehaviour", "useGUILayout"}, new List<string>(){"UnityEngine.Texture2D", "alphaIsTransparency"}, new List<string>(){"UnityEngine.Security", "GetChainOfTrustValue"}, new List<string>(){"UnityEngine.CanvasRenderer", "onRequestRebuild"}, new List<string>(){"UnityEngine.Light", "areaSize"}, new List<string>(){"UnityEngine.AnimatorOverrideController", "PerformOverrideClipListCleanup"}, new List<string>(){"UnityEngine.Input", "IsJoystickPreconfigured"}, #if !UNITY_WEBPLAYER new List<string>(){"UnityEngine.Application", "ExternalEval"}, #endif new List<string>(){"UnityEngine.GameObject", "networkView"}, //4.6.2 not support new List<string>(){"UnityEngine.Component", "networkView"}, //4.6.2 not support new List<string>(){"System.IO.FileInfo", "GetAccessControl", "System.Security.AccessControl.AccessControlSections"}, new List<string>(){"System.IO.FileInfo", "SetAccessControl", "System.Security.AccessControl.FileSecurity"}, new List<string>(){"System.IO.DirectoryInfo", "GetAccessControl", "System.Security.AccessControl.AccessControlSections"}, new List<string>(){"System.IO.DirectoryInfo", "SetAccessControl", "System.Security.AccessControl.DirectorySecurity"}, new List<string>(){"System.IO.DirectoryInfo", "CreateSubdirectory", "System.String", "System.Security.AccessControl.DirectorySecurity"}, new List<string>(){"System.IO.DirectoryInfo", "Create", "System.Security.AccessControl.DirectorySecurity"}, }; }
最新发布
07-07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值