Handle multiple WCF service references behind a injection-able interface - wcf

I have an assembly in my project that connects to four WCF services offered by a production and test version of On-prem Kofax TotalAgility. There are two main services and each service has a production and test instance, so in total 4.
Now, I'm wondering if there is a way to have a few interfaces hide the complex contract generated by the WCF wizard. I made the placeholder IActivityService.cs and IJobService.cs interfaces but I'm struggling with how do I inject it into the main project and set it in program.cs. Based on a config flag in the main API projects, I want to use either the staging or the production WCF service. Having this interface approach, I can expose the methods only needed. Here is an updated interface:
public interface IKtaActivityService
{
Task<bool> TakeActivityFromJob(string sessionId, string jobIdentity);
Task CompleteActivityAsync(string sessionId, string jobIdentity, IDictionary<string, object> jobActivityOutput);
}
And
public interface IKtaJobService
{
Task<bool> StartJob(string sessionId, string jobIdentity);
}
So, I need to inject these two interfaces and configure them at setup to correctly encapsulate staging or production.

Related

How to configure AutoMapper 9.0 in IIS hosted WCF application

I want to use AutoMapper 9.0 in a WCF project containing several services that will be hosted in IIS. I've only found one other related SO question but its dealing with a 10 year old version of AutoMapper and is not asking the same question. Its answer is similar to the top hits on Google which suggest using a ServiceBehavior but that doesn't seem applicable when I want multiple services to use the same mapper. The defense rests.
In a web project, you might create a static MapperConfiguration in the Global.asax when the application starts, but WCF doesn't have a Global.asax. It looks like there are a few options for executing initialization code in WCF:
Include an AppInitialize() method in the App_Code folder. This will be dynamically compiled at runtime and people have complained that it can have missing reference issues in IIS so I'm not confident AutoMapper or its dependencies will be found once deployed to IIS.
Create a custom ServiceHost. This seems like it would execute once when the application starts, but also looks like it ignores the web.config configuration, which I don't want.
Use the Configure method per service. This has the same drawback as #2 and also I become concerned with thread safety (as in the ServiceBehavior approach) since two services could try to initialize the MapperConfiguration at once.
I considered just creating a class with a static property that would create a static MapperConfiguration or IMapper instance if it was not already created, but as in #3, I'm worried this may not be thread safe. Maybe if I did something like this?
public static class MapperConfig
{
private static IMapper _modelMapper;
private static readonly object _mapperLocker = new object();
public static IMapper ModelMapper
{
get
{
lock(_mapperLocker)
{
if (_modelMapper == null)
{
var config = new MapperConfiguration(cfg => cfg.AddProfile(new MappingProfile1()));
_modelMapper = config.CreateMapper();
}
}
return _modelMapper;
}
}
}
Where two services may call ModelMapper simultaneously. Another downside of this is the first request to any service will have to wait for the mapping to compile, but I'm not sure I can get away from that. I definitely don't want it compiling the mappings per call and would prefer not to even have to do it per service. Can you advise on the thread safety of MapperConfiguration and the best way to use it in IIS-hosted WCF?

ASP.NET Core Dependency Injection Evaluation of Tree

Is there an easy way to evaluate that the dependencies are available within the DI container for either a given service or all services? (Specifically at build time)
I have a couple of Azure Functions running that I manually build the DI container for to keep the content to a minimum and when the dependency tree changes I have to remember to add the new dependency to the function. If I don't I get an error when the function executes the first time not when I build it to republish.
Is there a best practice to follow with this? Can it be achieved with some sort of unit test?
I don't think there is a way to validate this at build time, but as you suggest, you could verify this with a unit test if you follow the usual extension approach to registering your services. Arrange the list of types that should be registered, call your reg extensions, and validate the contents. The only thing I don't think you can do is confirm they're registered with the correct lifetime.
public static IServiceCollection AddFunctionsServices(this IServiceCollection services)
{
return services
.AddTransient<Foo>()
.AddTransient<Bar>()
.AddTransient<Baz>();
}
[Fact]
public void RegisteredServices()
{
var types = new List<Type>{ typeof(Foo), typeof(Bar), typeof(Baz) };
var provider = new ServiceCollection()
.AddFunctionsServices()
.AddSomeOtherServices()
.BuildServiceProvider();
foreach(var t in types)
Assert.NotNull(provider.GetService<t>());
}
If registration happens in a separate library used by different apps (I actually do this myself with a library that supports Functions, web apps, and command-line utilities), you can easily set up different tests for the list of services required by each library consumer.

Encapsulating WCF Proxies in Static Classes

I am designing a web service which will call different external web services according to the properties of a given object (a "request", for instance). A reference to these web services is added through the "Add Web Reference" menu in Visual Studio 2008, which, as you know, creates a proxy class for each endpoint which inherits from System.ServiceModel.ChannelBase<ISomeInterface> (where ISomeInterface is the endpoint defined by the specific service's WSDL).
The question is that I would like to encapsulate all those proxies in a single ServiceManager (for instance) static class containing, for example, an internal list of all the proxies, so that, on the one hand, all calls to a given service may go through ServiceManager instead of being scattered around the main application, and, on the other hand, new services which may be added latter can be made known to ServiceManager by a simple addition of a reference to the new proxy class.
I thought about desinging ServiceManager like
public static class ServiceManager
{
#region Properties
public static Dictionary<string, TProxy> ServiceList { get; private set; }
#endregion
}
but I don't know what I should replace TProxy by so that all of the different proxies can be called by using ServiceManager.ServiceList["ServiceName"]. Can anyone please help me out with this?
Since each service implements a different interface, it would have to be object... Unless you can create a common base interface, make the proxies inherit from that interface, and then create a List<MyBaseInterface>.
Why can't you just have one property on your class per proxy? At least then you could access the proxies in a strongly-typed way.
Do not reuse proxies. Re-instantiate them. Magic strings to differentiate between proxies are equally bad.
You are better off using static factories that return your service proxies than you are keeping only one instance of them.
Something like this:
public static class ServiceFactory
{
public static Proxy CreateProxy();
public static Proxy2 CreateProxy2();
// etc.
}

Naming conventions for a project containg only WCF ServiceReferences?

Let's say we have a back-end that needs to talk to N external systems using some kind of Web Services.
What I do is: Create a separate project and generate there the proxy classes (using the service's WSDL in the WCF Service Reference dialog).
About the project name suffix:
I firstly though XxAdapter. But then, I started creating classes with additional logic like CircuitBreakers so I ended up with XxAgent (from ServiceAgent).
What should be the "correct" suffix for the name of such projects.
The most appropriate suffix is "Proxies" because of several reasons:
Your component contains all the web service proxy classes.
In case that you want to make calls to several service proxies transparent, you can create a new class named MyLocalProxy, and perform the action
public class MyServiceProxy
{
public void DoSomething()
{
var serviceProxy1 = new ServiceProxy1();
serviceProxy1.DoOneThing();
var serviceProxy2 = new ServiceProxy2();
serviceProxy2.DoAnotherThing();
}
}
The additional class helps you to not depend on concrete service proxies, so you can interchange them as you wish.
Cheers.

How do I pass a service to another plugin?

I have a plugin that I will instantiate at runtime and I want to pass it a WCF service from the application host. The application host is responsible for creating the connection to the service. The reason for this is that a single service can be used by multiple plugins, but the plugins should only know about its interface since there may be several implementation of IMyPluginServices. For instance, the Run method of the plugin instance would be:
public void Run(IMyPluginServices services)
{
services.DoSomething();
}
The problem I am running into is that I don't know how to create a service of type IMyPluginServices and pass it to the Run function. The service reference generated by VS 2010 doesn't seem to create an object of type IMyPluginServices that I can pass to it. Any help would be greatly appreciated. Thanks.
When you add a service reference in VS 2010 for a service it generates an interface named IMyService which contains methods for each OperationContract in your service. It also generates a concrete class named MyServiceClient, which can be constructed and then used to invoke your service.
Now, the problem that you're running into, I believe, is that MyServiceClient is a subclass of ClientBase<IMyService>, and does not implement the generated IMyService interface (which is a real pain).
To get around this problem I ended up making a new interface:
public interface IMyServiceClient : IMyService, IDisposable, ICommunicationObject
{
}
(Note: IDisposable and ICommunicationObject are only required if you want your module to be able to detect/react to faulted channels and other such things).
I then extend MyServiceClient with a partial class (in the assembly that contains my WCF Service reference):
public partial class MyServiceClient : IMyServiceClient
{
}
Now in my modules I can accept an IMyServiceClient instead of an IMyService, and still execute all of the methods that I need to. The application in control of the modules can still create instances of MyServiceClient as it always did.
The beauty of this is that your new interface and partial class don't need any actual code - the definitions suffice to get the job done.