Unity - Dependency Injection Types
You can use RegisterType or App.config to achieve the same objectives.
static void Main(string[] args)
{
IUnityContainer container = new UnityContainer();
UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
section.Containers.Default.Configure(container);
//// You can override with container.RegisterType();
CoreService svc = container.Resolve();
svc.ExecuteService();
}
Sample Service classes
public class CoreService
{
[Dependency]
public IService MyService { get; set; }
public void ExecuteService()
{
MyService.SayHello("Jeremy");
}
}
public class CustomerService : IService
{
string IService.SayHello(string Username)
{
return "Customer Service " + Username;
}
}
Sample App.Config File
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="unity"
type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,
Microsoft.Practices.Unity.Configuration" />
</configSections>
<unity>
<containers>
<container>
<types>
<type type="Services.IService, Services" mapTo="Services.CustomerService, Services"></type>
</types>
</container>
</containers>
</unity>
</configuration>
static void Main(string[] args)
{
IUnityContainer container = new UnityContainer();
UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
section.Containers.Default.Configure(container);
//// You can override with container.RegisterType
CoreService svc = container.Resolve
svc.ExecuteService();
}
Sample Service classes
public class CoreService
{
[Dependency]
public IService MyService { get; set; }
public void ExecuteService()
{
MyService.SayHello("Jeremy");
}
}
public class CustomerService : IService
{
string IService.SayHello(string Username)
{
return "Customer Service " + Username;
}
}
Sample App.Config File
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="unity"
type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,
Microsoft.Practices.Unity.Configuration" />
</configSections>
<unity>
<containers>
<container>
<types>
<type type="Services.IService, Services" mapTo="Services.CustomerService, Services"></type>
</types>
</container>
</containers>
</unity>
</configuration>
Comments