How do I pass values to the constructor on my wcf

2018-12-31 16:49发布

I would like to pass values into the constructor on the class that implements my service.

However ServiceHost only lets me pass in the name of the type to create, not what arguments to pass to its contrstructor.

I would like to be able to pass in a factory that creates my service object.

What I have found so far:

8条回答
孤独总比滥情好
2楼-- · 2018-12-31 17:14

Mark's answer with the IInstanceProvider is correct.

Instead of using the custom ServiceHostFactory you could also use a custom attribute (say MyInstanceProviderBehaviorAttribute). Derive it from Attribute, make it implement IServiceBehavior and implement the IServiceBehavior.ApplyDispatchBehavior method like

// YourInstanceProvider implements IInstanceProvider
var instanceProvider = new YourInstanceProvider(<yourargs>);

foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
{
    foreach (var epDispatcher in dispatcher.Endpoints)
    {
        // this registers your custom IInstanceProvider
        epDispatcher.DispatchRuntime.InstanceProvider = instanceProvider;
    }
}

Then, apply the attribute to your service implementation class

[ServiceBehavior]
[MyInstanceProviderBehavior(<params as you want>)]
public class MyService : IMyContract

The third option: you can also apply a service behavior using the configuration file.

查看更多
临风纵饮
3楼-- · 2018-12-31 17:18

I worked from Mark's answer, but (for my scenario at least), it was needlessly complex. One of the ServiceHost constructors accepts an instance of the service, which you can pass in directly from the ServiceHostFactory implementation.

To piggyback off Mark's example, it would look like this:

public class MyServiceHostFactory : ServiceHostFactory
{
    private readonly IDependency _dep;

    public MyServiceHostFactory()
    {
        _dep = new MyClass();
    }

    protected override ServiceHost CreateServiceHost(Type serviceType,
        Uri[] baseAddresses)
    {
        var instance = new MyService(_dep);
        return new MyServiceHost(instance, serviceType, baseAddresses);
    }
}

public class MyServiceHost : ServiceHost
{
    public MyServiceHost(MyService instance, Type serviceType, params Uri[] baseAddresses)
        : base(instance, baseAddresses)
    {
    }
}
查看更多
登录 后发表回答