Skip to content

Instantly share code, notes, and snippets.

@clemensv
Last active December 1, 2015 11:39
Show Gist options
  • Save clemensv/03f473a4b5baa137a146 to your computer and use it in GitHub Desktop.
Save clemensv/03f473a4b5baa137a146 to your computer and use it in GitHub Desktop.

The class in this gist is a simple generic callback instance provider for WCF that allows straightforward creation of parameterized instances from the hosting context without having to drag in a whole dependency injection framework that supports this.

var host = new ServiceHost(typeof(MyServiceImpl))
var endpoint = host.AddServiceEndpoint(contract,
                                       binding,
                                       address);
endpoint.EndpointBehaviors.Add(
        new InstanceFactory<MyServiceImpl>(() => new MyServiceImpl(param, param)));
namespace Samples
{
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
delegate T InstanceFactoryCallback<out T>();
class InstanceFactory<T> : IContractBehavior, IInstanceProvider, IEndpointBehavior
{
readonly InstanceFactoryCallback<T> callback;
public InstanceFactory(InstanceFactoryCallback<T> callback)
{
this.callback = callback;
}
void IContractBehavior.Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
{
}
void IContractBehavior.ApplyDispatchBehavior(
ContractDescription contractDescription,
ServiceEndpoint endpoint,
DispatchRuntime dispatchRuntime)
{
dispatchRuntime.InstanceProvider = this;
}
void IContractBehavior.ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
}
void IContractBehavior.AddBindingParameters(
ContractDescription contractDescription,
ServiceEndpoint endpoint,
BindingParameterCollection bindingParameters)
{
}
void IEndpointBehavior.Validate(ServiceEndpoint endpoint)
{
}
void IEndpointBehavior.AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
void IEndpointBehavior.ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
endpointDispatcher.DispatchRuntime.InstanceProvider = this;
}
void IEndpointBehavior.ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
}
public object GetInstance(InstanceContext instanceContext)
{
return this.callback();
}
public object GetInstance(InstanceContext instanceContext, Message message)
{
return this.callback();
}
public void ReleaseInstance(InstanceContext instanceContext, object instance)
{
var disposable = instance as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment