WCF Rest Service使用Unity实现依赖注入

微软企业库v5.0可以对WCF rest 服务实现依赖注入
 1  public  interface IExampleService
 2     {
 3         IEnumerable<Example> GetAll();       
 4     }
 5  
 6     public  class ExampleService : IExampleService
 7    {
 8         private  readonly IExampleRepository ExampleRepository;
 9         private  readonly IUnitOfWork unitOfWork;
10         public ConfigService(IConfigRepository exampleRepository, IUnitOfWork unitOfWork)
11        {
12             this.ExampleRepository = exampleRepository;
13             this.unitOfWork = unitOfWork;
14        }
15  
16         public IEnumerable<Config> GetAll()
17        {
18             var categories = ConfigRepository.GetAll();
19             return categories;
20        }
21     }
22 


  1  using System.ServiceModel.Dispatcher;
  2  using System.ServiceModel;
  3  using System.ServiceModel.Description;
  4  using System.ServiceModel.Channels;
  5  using System.Collections.ObjectModel;
  6  
  7  namespace Example.Rest.Helpers
  8 {
  9      public  class IoC
 10     {
 11          public  class UnityWebServiceHost : WebServiceHost
 12         {
 13              protected IUnityContainer _container;
 14  
 15              public UnityWebServiceHost()
 16             {
 17             }
 18  
 19              public UnityWebServiceHost( object singletonInstance,  params Uri[] baseAddresses)
 20                 :  base(singletonInstance, baseAddresses)
 21             {
 22             }
 23  
 24              public UnityWebServiceHost(IUnityContainer container, Type serviceType,  params Uri[] baseAddresses)
 25                 :  base(serviceType, baseAddresses)
 26             {
 27                  if (container ==  null)
 28                 {
 29                      throw  new ArgumentNullException( " container ");
 30                 }
 31                 _container = container;
 32             }
 33  
 34              protected  override  void OnOpening()
 35             {
 36                 Description.Behaviors.Add( new UnityServiceBehaviour(_container));
 37                  base.OnOpening();
 38             }
 39         }
 40  
 41          public  class UnityInstanceProvider : IInstanceProvider
 42         {
 43              private  readonly Type _serviceType;
 44              private  readonly IUnityContainer _container;
 45  
 46              public UnityInstanceProvider(IUnityContainer container, Type serviceType)
 47             {
 48                 _serviceType = serviceType;
 49                 _container = container;
 50             }
 51  
 52  
 53              public  object GetInstance(InstanceContext instanceContext)
 54             {
 55                  return GetInstance(instanceContext,  null);
 56             }
 57  
 58              public  object GetInstance(InstanceContext instanceContext, Message message)
 59             {
 60                  return _container.Resolve(_serviceType);
 61             }
 62  
 63              public  void ReleaseInstance(InstanceContext instanceContext,  object instance)
 64             {
 65             }
 66  
 67         }
 68  
 69          public  class HttpContextLifetimeManager<T> : LifetimeManager, IDisposable
 70         {
 71              public  override  object GetValue()
 72             {
 73                  return HttpContext.Current.Items[ typeof(T).AssemblyQualifiedName];
 74             }
 75              public  override  void RemoveValue()
 76             {
 77                 HttpContext.Current.Items.Remove( typeof(T).AssemblyQualifiedName);
 78             }
 79              public  override  void SetValue( object newValue)
 80             {
 81                 HttpContext.Current.Items[ typeof(T).AssemblyQualifiedName] = newValue;
 82             }
 83              public  void Dispose()
 84             {
 85                 RemoveValue();
 86             }
 87  
 88         }
 89  
 90          public  class UnityServiceBehaviour : IServiceBehavior
 91         {
 92              private  readonly IUnityContainer _container;
 93  
 94              public UnityServiceBehaviour(IUnityContainer container)
 95             {
 96                 _container = container;
 97             }
 98  
 99              public  void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
100             {
101                  foreach ( var endpointDispatcher  in
102                     serviceHostBase.ChannelDispatchers.OfType<ChannelDispatcher().SelectMany(
103                         channelDispatcher => channelDispatcher.Endpoints))
104                 {
105                     endpointDispatcher.DispatchRuntime.InstanceProvider =  new UnityInstanceProvider(_container, serviceDescription.ServiceType);
106                 }
107             }
108  
109              public  void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase,
110                                              Collection<ServiceEndpoint> endpoints,
111                                              BindingParameterCollection bindingParameters)
112             {
113             }
114  
115              public  void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
116             {
117             }
118         }
119     }
120 }
121  
122     [ServiceContract]
123     [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
124     [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
125      public  class ExampleApi
126     {
127          private  readonly IExampleService exampleService;
128  
129          public ExampleApi(IExampleService exampleService)
130         {
131             this.exampleService = exampleService;      
132         }
133  
134          public exampleApi()
135         {           
136         }
137  
138         [WebGet(UriTemplate =  "")]
139          public IEnumerable<Example> GetAll()
140         {
141              var examples = exampleService.GetAll();        
142             return examples;  
143         }
144      }


 1     public  class Global : HttpApplication
 2     {
 3          void Application_Start( object sender, EventArgs e)
 4         {
 5             RegisterRoutes();          
 6         }
 7  
 8          private  void RegisterRoutes()
 9         {
10             RouteTable.Routes.Add( new ServiceRoute( " ExampleApi "new UnityServiceHostFactory(),  typeof(ExampleApi)));
11         }
12            
13          private  static  void RegisterTypes(IUnityContainer container)
14         {
15             container.RegisterType<IDatabaseFactory, DatabaseFactory>( new IoC.HttpContextLifetimeManager<IDatabaseFactory>());
16             container.RegisterType<IUnitOfWork, UnitOfWork>( new IoC.HttpContextLifetimeManager<IUnitOfWork>());
17  
18              //  repositories
19              container.RegisterType<IExampleRepository, ExampleRepository>( new IoC.HttpContextLifetimeManager<IExampleRepository>());
20  
21              //  services
22              container.RegisterType<IExampleService, ExampleService>( new IoC.HttpContextLifetimeManager<IExampleService>());
23         }
24  
25          public  class UnityServiceHostFactory : WebServiceHostFactory
26         {
27              protected  override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
28             {
29                  var container =  new UnityContainer();
30  
31                 RegisterTypes(container);
32  
33                  return  new IoC.UnityWebServiceHost(container, serviceType, baseAddresses);
34             }
35         }
36     }
原文地址 请点击

你可能感兴趣的:(service)