C# Unity IOC register new types in App.conf

Asked at 2016-12-29 21:49:50Z
  • 5 Subscribers
  • 114 Views
0

Currently in my winforms application all my types are registerd in Main method. Am looking for solution how can i register all new types inside App.conf? Is that posible ?

This i currently use in my app:

    [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 answers in total

1
Damian Posted at 2016-12-29 22:12:09Z

It is possible to register types inside app.config. I wrote simple console application to illustrate that:

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>();
        }
    }
}

And app.config (TheLogger class is registered as an implementation of 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>

For more details check this MSDN page.

Answer this questsion