- Unity via configuration - property dependency injection in generic base class
- public interface ITestService
- {
- ...
- }
- public class BaseTestServiceImpl<T> : ITestService, IDisposable where T : class
- {
- protected T GenericProperty;
- public IOtherService OtherService;
- public void ExampleMethodFromBase()
- {
- OtherService.DoSomething();
- }
- public void Dispose()
- {
- ....
- }
- }
- public class SpecificTestServiceImpl : BaseTestServiceImpl<SomeType>
- {
- public void ExampleMethodFromSpecific()
- {
- OtherService.DoSomethingElse();
- }
- }
- public class TestController : Controller
- {
- [Dependency("TestService")]
- public BaseTestServiceImpl<SomeType> TestService { get; set; }
- public JsonResult TestAction()
- {
- TestService.ExampleMethodFromSpecific();
- }
- }
- <?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">
- <container>
- <alias alias="transient" type="Microsoft.Practices.Unity.TransientLifetimeManager, Microsoft.Practices.Unity" />
- <alias alias="MyType" type="SomeType" />
- <register name="otherService" type="IOtherService" mapTo="OtherServiceImpl">
- <lifetime type="singleton" />
- </register>
- <register type="ITestService" mapTo="BaseTestServiceImpl`1[]">
- <lifetime type="transient" />
- <property name="OtherService" dependencyName="otherService" />
- </register>
- <register name="TestService" type="BaseTestServiceImpl`1[MyType]" mapTo="SpecificTestServiceImpl">
- <lifetime type="singleton" />
- </register>
- </container>
- </unity>
- </configuration>
- OtherService.DoSomethingElse();