Super detailed introduction to Unity and how to use it

foreword

As one of the game development tools, the Unity engine is not much to say about its popularity. For developers, all they need to do is to master the use of various functions of Unity to help themselves develop games. For this reason, there is a simple introduction to the unity engine and its use in this article.


1. Introduction to IOC

IOC (Inversion of Control) , Chinese translation is inversion of control, also known as "dependency injection" (DI = Dependence Injection)

The basic concept of IOC is: do not create objects, but describe how to create them.

Do not connect directly to objects and services in the code, but describe which component needs which service in the configuration file. The container is responsible for tying these together.

The principle is based on The Hollywood Principle of OO design principles: Don't call us, we'll call you (don't call me, I'll call you).

That is to say, all components are passive (Passive), and all component initialization and invocation are the responsibility of the container. Components are in a container, which is managed by the container.

Simply put, the application itself is not responsible for the creation and maintenance of dependent objects, but to an external container to be responsible. In this way, the control right is transferred from the application to the external IoC container, that is, the control right realizes the so-called inversion.

For example, an instance of type B needs to be used in type A, and the creation of B instance is not responsible for A, but is created through an external container. It is of great significance to realize the activation of the target Controller through IoC.

2. Get Unity

Currently popular IoC frameworks, such as AutoFac, Castle Windsor, Unity, http://Spring.NET , StructureMap and Ninject, etc.

You can get the latest version of Unity directly in Nuget. I'm using Unity, not Unity for mvc.

3. Introduction to Unity####

Unit is a lightweight and extensible dependency injection container implemented in C# by the Microsoft patterns & practices group. We can configure the relationship between objects in the form of code or XML configuration files.

Calling the Unity container directly at runtime can get the objects we need to build loosely coupled applications.

For small projects: just implement it in code

For medium to large projects: it is better to use a configuration file

Since Unity is an Ioc framework, it also satisfies the commonality of Ioc. Dependency injection is divided into three forms, namely constructor injection, property (setting) injection and interface injection.

4. Unity API (part)

UnityContainer.RegisterType<ITFrom,TTO>();

UnityContainer.RegisterType< ITFrom, TTO>("keyName");

IEnumerable<T> databases = UnityContainer.ResolveAll<T>();

IT instance = UnityContainer.Resolve<IT>();

T instance = UnityContainer.Resolve<T>("keyName");

UnitContainer.RegisterInstance<T>("keyName",new T());

UnityContainer.BuildUp(existingInstance);

IUnityContainer childContainer1 = parentContainer.CreateChildContainer();

5. Use Unity

If the Unity library installed by NuGut is used, the reference will be automatically added to the project

Microsoft.Practices.Unity.dll

Microsoft.Practices.Unity.Configuration.dll

Microsoft.Practices.Unity.RegistrationByConvention.dll

1. Programmatically implement injection

Using Unity to manage the relationship between objects and objects can be divided into the following steps:

A. Create a UnityContainer object

B. Register the relationship between objects and objects through the RegisterType method of the UnityContainer object

C. Obtain the object associated with the specified object through the Resolve method of the UnityContainer object

The injection code is as follows:

/// <summary>
    /// 商品
    /// </summary>
    public interface IProduct
    {
        string ClassName { get; set; }
        string ShowInfo();
    }
    /// <summary>
    /// 牛奶
    /// </summary>
    public class Milk : IProduct
    {
        public string ClassName { get; set; }
        public void ShowInfo()
        {
            return string.Format("牛奶:{0}", ClassName);
        }
    }
    /// <summary>
    /// 糖
    /// </summary>
    public class Sugar : IProduct
    {
        public string ClassName { get; set; }
        public void ShowInfo()
        {
            return string.Format("糖:{0}", ClassName);
        }
    }
/// <summary>
        /// 代码注入
        /// </summary>
        public string ContainerCode()
        {
            IUnityContainer container = new UnityContainer();
            container.RegisterType<IProduct, Milk>();  //默认注册(无命名),如果后面还有默认注册会覆盖前面的
            container.RegisterType<IProduct, Sugar>("Sugar");  //命名注册
            IProduct _product = container.Resolve<IProduct>();  //解析默认对象
            _product.ClassName = _product.GetType().ToString();
            string str1 = _product.ShowInfo();<br>
            IProduct _sugar = container.Resolve<IProduct>("Sugar");  //指定命名解析对象
            _sugar.ClassName = _sugar.GetType().ToString();
            string str2 = _sugar.ShowInfo();<br><br>       StringBuilder strs = new StringBuilder();<br>       strs.Append(str1);<br>       strs.Append(str2);<br>
            IEnumerable<IProduct> classList = container.ResolveAll<IProduct>(); //获取容器中所有IProduct的注册的已命名对象
            foreach (var item in classList)
            {
                item.ClassName = item.GetType().ToString();
                strs.Append(item.ShowInfo());
            }return strs.ToString();
        }</pre>
结果:

牛奶:UnityTest.Milk 

糖:UnityTest.Sugar 

糖:UnityTest.Sugar

2. Configuration file method

Configuring Unity information through configuration files requires the following steps:

A. Register a section named unity under the <configSections> configuration section of the configuration file

B. Add Unity configuration information under the <configuration> configuration section

C. Read the configuration information in the code and load the configuration into the UnityContainer

The content of the configuration file is as follows:

<configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <!--声明容器-->
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity>
    <!--定义类型别名-->
    <aliases>
      <add alias="IProduct" type="UnityTest.IProduct,UnityTest" />
      <add alias="Milk" type="UnityTest.Milk,UnityTest" />
      <add alias="Sugar" type="UnityTest.Sugar,UnityTest" />
    </aliases>
    <!--容器-->
    <container name="MyContainer">
      <!--映射关系-->
      <register type="IProduct"  mapTo="Milk"></register>
      <register type="IProduct"  mapTo="Sugar" name="Sugar"></register>
    </container>
  </unity></pre>

添加引用:

using System.Configuration;

using Microsoft.Practices.Unity.Configuration;

<pre class="code" data-lang="javascript" style="box-sizing: border-box; margin: 0px; padding: 0px; white-space: pre-wrap;">/// <summary>
        /// 配置文件注入
        /// </summary>
        public string ContainerConfiguration()
        {
            //加载容器配置
            IUnityContainer container = new UnityContainer();
            container.LoadConfiguration("MyContainer");
            UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");//获取指定名称的配置节  
            section.Configure(container, "MyContainer");//获取特定配置节下已命名的配置节<container name='MyContainer'>下的配置信息
            IProduct classInfo = container.Resolve<IProduct>("Sugar");
            classInfo.ClassName = classInfo.GetType().ToString();
            return classInfo.ShowInfo();
        }</pre>

结果:

糖:UnityTest.Sugar

If the system is relatively large, the dependencies between objects may be complicated, and eventually the configuration file will become very large, so we need to separate the Unity configuration information from App.config or web.config to a separate In the configuration file, such as Unity.config, the implementation method can refer to the following code:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
  </system.web>
  <configSections>
    <!--声明容器-->
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity>
    <!--定义类型别名-->
    <aliases>
      <add alias="IProduct" type="UnityTest.IProduct,UnityTest" />
      <add alias="Milk" type="UnityTest.Milk,UnityTest" />
      <add alias="Sugar" type="UnityTest.Sugar,UnityTest" />
    </aliases>
    <!--容器-->
    <container name="MyContainer">
      <!--映射关系-->
      <register type="IProduct"  mapTo="Milk"></register>
      <register type="IProduct"  mapTo="Sugar" name="Sugar"></register>
    </container>
  </unity>
</configuration></pre>

Registration code:

/// <summary>
        /// 配置文件注入
        /// </summary>
        public string ContainerConfiguration2()
        {
            IUnityContainer container = new UnityContainer();
            string configFile = "Unity.config";
            var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = configFile };
            //从config文件中读取配置信息
            Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            //获取指定名称的配置节
            UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
            //载入名称为FirstClass 的container节点
            container.LoadConfiguration(section, "MyContainer");
            IProduct classInfo = container.Resolve<IProduct>("Sugar");
            classInfo.ClassName = classInfo.GetType().ToString();
            return classInfo.ShowInfo();
        }</pre>

结果:

糖:UnityTest.Sugar

Guess you like

Origin blog.csdn.net/bycw666/article/details/123657714