C# Unity IOC register new types in App.conf

969 Views Asked by At

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

There are 1 best solutions below

1
On BEST ANSWER

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.