C#Unity IOC在App.conf

时间:2016-12-29 21:49:51

标签: c# dependency-injection inversion-of-control unity-container ioc-container

目前在我的winforms应用程序中,我的所有类型都以Main方法注册。 我正在寻找解决方案如何在App.conf内注册所有新类型? 那可能吗?

我目前在我的应用中使用:

    [STAThread]
    static void Main(string[] args)
    {
        UnityContainer ioc = new UnityContainer();

        // This move in app.conf
        ioc.RegisterType<Customer>();
        ioc.RegisterType<MainWindow>();
        ioc.RegisterType<IDatabase, MySqlDatabase>();

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(ioc.Resolve<MainWindow>());
    }

1 个答案:

答案 0 :(得分:1)

可以在app.config中注册类型。我编写了简单的控制台应用程序来说明:

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace MyNamespace
{
    public interface ILogger
    { }

    public class TheLogger : ILogger
    { }

    class Program
    {
        private static void Main(string[] args)
        {
            IUnityContainer container = new UnityContainer();
            container.LoadConfiguration();

            var logger = container.Resolve<ILogger>();
        }
    }
}

并且app.config(TheLogger类被注册为ILogger的实现):

<?xml version="1.0" encoding="utf-8" ?>
<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">
    <namespace name="MyNamespace" />
    <assembly name="MyApp" />
    <container>
      <register type="ILogger" mapTo="TheLogger" />
    </container>
  </unity>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
</configuration>

有关详细信息,请查看此MSDN page