Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 7th, 2012  |  syntax: None  |  size: 1.91 KB  |  hits: 10  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Unity via configuration - property dependency injection in generic base class
  2. public interface ITestService
  3. {
  4.     ...
  5. }
  6.        
  7. public class BaseTestServiceImpl<T> : ITestService, IDisposable where T : class
  8. {
  9.     protected T GenericProperty;
  10.  
  11.     public IOtherService OtherService;
  12.  
  13.     public void ExampleMethodFromBase()
  14.     {
  15.         OtherService.DoSomething();
  16.     }
  17.  
  18.     public void Dispose()
  19.     {
  20.         ....
  21.     }
  22. }
  23.        
  24. public class SpecificTestServiceImpl : BaseTestServiceImpl<SomeType>
  25. {
  26.     public void ExampleMethodFromSpecific()
  27.     {
  28.         OtherService.DoSomethingElse();
  29.     }
  30. }
  31.        
  32. public class TestController : Controller
  33. {
  34.     [Dependency("TestService")]
  35.     public BaseTestServiceImpl<SomeType> TestService { get; set; }
  36.  
  37.     public JsonResult TestAction()
  38.     {
  39.         TestService.ExampleMethodFromSpecific();
  40.     }
  41. }
  42.        
  43. <?xml version="1.0" encoding="utf-8" ?>
  44. <configuration>
  45.  
  46.     <configSections>
  47.     <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  48.     </configSections>
  49.  
  50.     <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
  51.     <container>
  52.         <alias alias="transient" type="Microsoft.Practices.Unity.TransientLifetimeManager, Microsoft.Practices.Unity" />
  53.         <alias alias="MyType" type="SomeType" />
  54.         <register name="otherService" type="IOtherService" mapTo="OtherServiceImpl">
  55.             <lifetime type="singleton" />
  56.         </register>
  57.         <register type="ITestService" mapTo="BaseTestServiceImpl`1[]">
  58.             <lifetime type="transient" />
  59.             <property name="OtherService" dependencyName="otherService" />
  60.         </register>
  61.         <register name="TestService" type="BaseTestServiceImpl`1[MyType]" mapTo="SpecificTestServiceImpl">
  62.             <lifetime type="singleton" />
  63.         </register>
  64.     </container>
  65.     </unity>
  66. </configuration>
  67.        
  68. OtherService.DoSomethingElse();