Making WCF OperationContext play nicely with DI and testing - wcf

I'm running a WCF service hosted in a Windows service; dependencies of the WCF service are injected via Unity, which is all good. As a result, the service is also easy to write unit tests for.
Recently, I added functionality to the service that makes use of the OperationContext to inspect incoming messages. Unfortunately this rather blows the testability of the service out of the water, owing to Microsoft's fondness for sealed and/or static classes and lack of interfaces and/or virtual methods.
So I turned to the .NET'ers favourite tool in this situation, a wrapper class. Since this is a common problem, someone's already done the hard work for us. So this adds a new dependency to my WCF service, an implementation of IOperationContext. This was no problem for my unit tests, NSubstitute is my mock framework of choice (like Moq, but without the curse of the .Object).
However, when I try to fire up the service for real, I have the following problem - the OperationContext which is being wrapped has not been initialised at the time the IoC container registrations are done. My initialisation code (using Unity here) is:
container.RegisterType<IOperationContext, OperationContextWrapper>(new InjectionConstructor(OperationContext.Current));
but at this point, OperationContext.Current is null, so Unity promptly throws an exception, and my dreams of retiring before 40 go up in smoke.
So, the question is: how do you get WCF to play nicely with DI and a wrapped OperationContext?

Maybe I'm not understanding, but I'm not sure why you want to inject OperationContext.Current into your wrapper. If OperationContextWrapper is wrapping OperationContext, than why not just have it's implementation interact directly with OperationContext.Current where it needs to? I presume the code you're trying to keep testable is not OperationContextWrapper, but rather the code that depends on it via the IOperationContext interface? Then who care what OperationContextWrapper does?

OperationContext.Current is a settable property. Can you change your test initialization to
OperationContext.Current = new OperationContextWrapper();
and have it work that way? If you need it in unity, you could also:
var oc = new OperationContextWrapper();
OperationContext.Current = oc;
container.RegisterInstance<IOperationContext>(oc);

You can also use Microsoft Fakes :
using (ShimsContext.Create())
{
ShimOperationContext shimOperationContext = new
ShimOperationContext(); shimOperationContext.SessionIdGet = () => "sessionId";
OperationContext.Current = shimOperationContext;
}

Related

What are the differences between BackgroundServices and SingletonServices?

I have a service which should begin when the server starts, and continue running for the entirety of the server lifetime. I would like to be able to manage the service (querying, modifying runtime options, etc) with a web frontend. While researching the best way to accomplish this, I came across two options: a scoped service with a singleton lifetime, and a backgroundservice/IHostedService. What are the differences between the two options, and when should one be used over the other?
Neither of those is actually a thing. The closest is the concept of a singleton and hosted services. A hosted service is a class that implements IHostedService and pretty much fits the bill of what you're looking for in that it will start at app startup and stop at app shutdown. ASP.NET Core 3.0 added a BackgroundService class, which is just an implementation of IHostedService with a lot of the cruft of defining what happens as start/stop/etc. covered. In practice, it usually makes more sense to inherit from BackgroundService, but you can also just implement IHostedService directly yourself.
"Singleton" is just a lifetime. All hosted services are registered with a singleton lifetime, but just because something is a singleton, doesn't mean it does anything special. You could, for example, register some random class as a singleton, and whenever it is injected, you'll always get the same instance. However, it will not do anything at startup or shutdown on its own.
Long and short, there are no differing options here. You're looking for a hosted service. That said, it only solves part of what you're looking for, in that it will "run" while the app is running. However, you can't really connect to it, or interact with it directly. It's not like a Web Api or something; it isn't exposed for HTTP requests, for example.
To "manage" it, you would have to expose some sort of API that would then interact with the service through code. For example, the docs provide an example of a queued background service that processes things added to the queue. However, to queue something, you would need to do something like create an API endpoint, inject the queue, and then use code to add a new item to the queue. Then, the actual hosted service would eventually pop that task from the queue and work on it.

NServiceBus Removing IBus - Utilising IPipelineContext and IMessageSession

I am in the process of migrating NServiceBus up to v6 and am at a roadblock in the process of removing reference to IBus.
We build upon a common library for many of our applications (Website, Micro Services etc) and this library has the concept of IEventPublisher which is essentially a Send and Publish interface. This library has no knowledge of NSB.
We can then supply the implementation of this IEventPublisher using DI from the application, this allows the library's message passing to be replaced with another technology very easily.
So what we end up with is an implementation similar to
public class NsbEventPublisher : IEventPublisher
{
IEndpointInstance _instance;
public NsbEventPublisher(IEndpointInstance endpoint)
{
instance = endpoint;
}
public void Send(object message)
{
instance.Send(message, sendOptions);
}
public void Publish(object message)
{
instance.Publish(message, sendOptions);
}
}
This is a simplification of what actually happens but illustrates my problem.
Now when the DI container is asked for an IEventPublisher it knows to return a NsbEventPublisher and it knows to resolve the IEndpointInstance as we bind this in the bootstrapper for the website to the container as a singleton.
All is fine and my site runs perfect.
I am now migrating the micro-services (running in NSB.Host) and the DI container is refusing to resolve IEndpointInstance when resolving the dependencies within a message handler. Reading the docs this is intentional and I should be using IMessageHandlerContext when in a message handler.
https://docs.particular.net/nservicebus/upgrades/5to6/moving-away-from-ibus
The docs even elude to the issue I have in the bottom example around the class MyContextAccessingDependency. The suggestion is to pass the message context through the method which puts a hard dependency on the code running in the context of a message handler.
What I would like to do is have access to a sender/publisher and the DI container can give me the correct implementation. The code does not need any concept of the caller and if it was called from a message handler or from a self hosted application that just wants to publish.
I see that there is two interfaces for communicating with the "Bus" IPipelineContext and IMessageSession which IMessageHandlerContext and IEndpointInstance interfaces extend respectively.
What I am wondering is there some unification of the two interfaces that gets bound by NSB into the container so I can accept an interface that sends/publishes messages. In a handler it is an IMessageHandlerContext and on my self hosted application the IEndPointInstance.
For now I am looking to change my implementation of IEventPublisher depending on application hosting. I was just hoping there might be some discussion about how this approach is modeled without a reliable interface to send/publish irrespective of what initiated the execution of the code path.
A few things to note before I get to the code:
The abstraction over abstraction promise, never works. I have never seen the argument of "I'm going to abstract ESB/Messaging/Database/ORM so that I can swap it in future" work. ever.
When you abstract message sending functionality like that, you'll lose some of the features the library provides. In this case, you can't perform 'Conversations' or use 'Sagas' which would hinder your overall experience, e.g. when using monitoring tools and watching diagrams in ServiceInsight, you won't see the whole picture but only nugets of messages passing through the system.
Now in order to make that work, you need to register IEndpointInstance in your container when your endpoint starts up. Then that interface can be used in your dependency injection e.g. in NsbEventPublisher to send the messages.
Something like this (depending which IoC container you're using, here I assume Autofac):
static async Task AsyncMain()
{
IEndpointInstance endpoint = null;
var builder = new ContainerBuilder();
builder.Register(x => endpoint)
.As<IEndpointInstance>()
.SingleInstance();
//Endpoint configuration goes here...
endpoint = await Endpoint.Start(busConfiguration)
.ConfigureAwait(false);
}
The issues with using IEndpointInstance / IMessageSession are mentioned here.

Task-based async calls using ChannelFactory and ChannelFactory caching

I'm working on a project that is consuming SOAP services via WCF. Initially, we used generated service references because it was easy to get started. This provides ChannelFactory caching and task-based async methods out of the box, which is clearly desirable.
We've recently switched to using service interfaces and instantiating our own ChannelFactory. We treat the ChannelFactory as a singleton object to cache it. On caching the ChannelFactory -- I've been told that a ChannelFactory can go bad if, for example, one of its channels fault. Is this a real concern?
My second question is in regards to using task-based async calls like the ones generated when using the service reference. How is this done when using a ChannelFactory<T>? I understand that you can annotate methods on T with [OperationContract(AsyncPattern = true)], but these return IAsyncResult and not Task.
Any help would be appreciated.

Passing client context using Unity in WCF service application

I have a WCF service application (actually, it uses WCF Web API preview 5) that intercepts each request and extracts several header values passed from the client. The idea is that the 'interceptor' will extract these values and setup a ClientContext object that is then globally available within the application for the duration of the request. The server is stateless, so the context is per-call.
My problem is that the application uses IoC (Unity) for dependency injection so there is no use of singleton's, etc. Any class that needs to use the context receives it via DI.
So, how do I 'dynamically' create a new context object for each request and make sure that it is used by the container for the duration of that request? I also need to be sure that it is completely thread-safe in that each request is truly using the correct instance.
UPDATE
So I realize as I look into the suggestions below that part of my problem is encapsulation. The idea is that the interface used for the context (IClientContext) contains only read-only properties so that the rest of the application code doesn't have the ability to make changes. (And in a team development environment, if the code allows it, someone will inevitably do it.)
As a result, in my message handler that intercepts the request, I can get an instance of the type implementing the interface from the container but I can't make use of it. I still want to only expose a read-only interface to all other code but need a way to set the property values. Any ideas?
I'm considering implementing two interfaces, one that provides read-only access and one that allows me to initialize the instance. Or casting the resolved object to a type that allows me to set the values. Unfortunately, this isn't fool-proof either but unless someone has a better idea, it might be the best I can do.
Read Andrew Oakley's Blog on WCF specific lifetime managers. He creates a UnityOperationContextLifetimeManager:
we came up with the idea to build a Unity lifetime manager tied to
WCF's OperationContext. That way, our container objects would live
only for the lifetime of the request...
Configure your context class with that lifetime manager and then just resolve it. It should give you an "operation singleton".
Sounds like you need a Unity LifetimeManager. See this SO question or this MSDN article.

how to create and manage wcf service clients?

At first I treated them as any dependency passing them in the ctor to the class consuming the service:
var serviceConsumer = new ServiceConsumer(new MailingServiceClient())
The problem was that once an exception was thrown from the service it entered a faulted state and would not reply to any requests, so re-initialization was due.
Further more, I became familiar with the fact that wcf services may not be disposed properly on several occasions, because the dispose method of the generated proxy is broken (calls close without checking the fault state) and encountered a couple of ways to overcome that:
wrapping every call to every service.
override the default IDisposable behavior of the scvutil.exe-generated class
Since I wouldn't like the consumer code to create the service client himself for testing reasons, my questions are:
how can I maintain a working un-faulted service?
how can I still use dependency injection for testability?
Found a nice solution.
a proxy generator that replaces the VS one, and generates a wrapper around the default proxy that deals with proxy faults, timeouts, and correct disposal.
http://wcfproxygenerator.codeplex.com/
seems to be working fine for me.