WCF: Make all calls wait when one specific interface is being called - c#

I have a WCF service with quite a few interfaces which only read data. There is however one interface that reloads data from the database and reinitialises some dictionaries. While this interface "Reload" is running I effectively want all other calls to be put "on hold" as they would read data of an unknown state (as I am using per-call)
[ServiceContract]
public interface IMyObject
{
[OperationContract]
string Reload();
[OperationContract]
string Read1();
[OperationContract]
string Read2();
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
class MyObject : IMyObject
{
public string Reload() { //Takes 5-10secs, called twice a day }
public string Read1() { //Wait for Reload() to finish if it's running}
public string Read2() { //Wait for Reload() to finish if it's running}
}
Is this possible in WCF? Or is there a best practise way around this problem?

I believe if you play with the ConcurrencyMode and set it to single you can achieve what you want.
Having said that, I had achieved what you want having a flag on my services. If you set a static flag other calls can check for that flag and do what ever you want them to do

Suggest you to:
Change InstanceContextMode.PerCall to InstanceContextMode.Single
Then add ConcurrencyMode = ConcurrencyMode.Multiple (will allow more than 1 execution in a time)
In your MyObject implementation manually deal with concurrency. Use simple lock or advanced mechanics, like ReaderWriterLockSlim.
Implementation with lock is as follows:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]
class MyObject: IMyObject
{
private readonly object lockObject = new object();
public string Reload()
{
lock (lockObject)
{
// Reload stuff
}
}
public string Read1()
{
lock (lockObject)
{
// Read1 stuff
}
}
public string Read2()
{
lock (lockObject)
{
// Read2 stuff
}
}
}
Drawbacks, that it won't allow you to call simultaneously Read1 and Read2. If you need this functionality, use ReaderWriterLockSlim instead of lock.

Related

Should I use response object or property for returning response

I have a requirement where I need to send SMS to our customers. For sending SMS we have multiple providers. To achieve this, I have designed an interface and created different classes for providers by implementing this interface
public interface IProvider
{
Task<bool> SendAsync(ProviderRequest providerRequest);
}
public class Provider1: IProvider
{
public async Task<bool> SendAsync(ProviderRequest providerRequest)
{
//call provider1
return somethingBool;
}
}
public class Provider2: IProvider
{
public async Task<bool> SendAsync(ProviderRequest providerRequest)
{
//call provider2
return somethingBool;
}
}
We want to extend the requirement to get back the response from the provider. Now, to implement this I can think of 2 ways.
Create a ProviderResponse object and map the response to it and return.
public interface IProvider
{
//Updated interface method just to be concise, this will be a new version of the method
Task<ProviderResponse> SendAsync(ProviderRequest providerRequest);
}
// response class
public class ProviderResponse
{
public bool IsSuccess { get; set; }
public string ProviderResponse { get; set; }
}
Add a getter property and fill it from provider concrete classes. The calling code will have an instance of the provider selected and can access this property. The return type of the method does not change.
public interface IProvider
{
Task<bool> SendAsync(ProviderRequest providerRequest);
string ProviderResponse { get; }
}
Which design I should go with? Where will be the best places to use these design solutions?
Seem the First approach look more valid.
Thread Safe
We can create a singleton object and save multiple object creation
Extend in Response Object:
If we are expecting more parameters in the future from Response, we can create a property in the object. In the second approach, we have to pollute the Interface to add more parameters.
Extend in Interface:
Suppose IProvider require one more function to expose which have a different response and different parameter. Then in the Second approach IProvider becomes a design issue, ProviderResponse output is responsible for which function.
So overall feel, the First approach looks more valid in terms of Thread Safe, Design, Performance, and extendable.

Long running initialisation of class fields in constructor

Say I have the class below
public class MyClass {
private readonly NinjaObject _myNinja;
MyClass(NinjaFactory ninjaFactory) {
_myNinja = ninjaFactory.CreateNinjaButItTakesTime();
}
public void NinjaAttack() {
_myNinja.Attack();
}
}
Now, the constructor should do everything to initialise the class and get it ready for use by the application, i.e., create the Ninja and have it ready to attack when called to do so. It's also a good idea to have your constructor perform their actions quickly. However, this may not be possible if the process of creating a Ninja takes a long time. I presume you could create the Ninja asynchronously through some kind of static factory method, but then you run the risk (at least theoretically) of the Ninja not being ready (i.e. a null object) to attack when called to do so by the application.
When you have fields of a class that are critical to how that class operates but can take a long time to construct, what is the best pattern to adopt in creating them? Keep it synchronous in the constructor, or apply some kind of asynchronous pattern?
I presume you could create the Ninja asynchronously through some kind of static factory method, but then you run the risk (at least theoretically) of the Ninja not being ready (i.e. a null object) to attack when called to do so by the application.
Well, this is where an async static factory method comes in handy:
public class MyClass
{
private readonly Ninja ninja;
private MyClass(Ninja ninja)
{
this.ninja = ninja;
}
public static async Task<MyClass> Create()
{
// Or however you create a ninja - ideally properly asynchronous
var ninja = await Ninja.Create();
return new MyClass(ninja);
}
public void NinjaAttack() => ninja.Attack();
}
You can't avoid it taking a long time - but you can make the creation asynchronous by leaving the constructor call right to the end. This basically works around the restriction that constructors can't be asynchronous.
An alternative - but a dangerous one - would be to start the task creating the ninja and pass that into the constructor, but use the result of the task later:
public class MyClass
{
private readonly Task<Ninja> ninjaTask;
public MyClass(Task<Ninja> ninjaTask)
{
this.ninjaTask = ninjaTask;
}
public void NinjaAttack() => ninjaTask.Result.Attack();
}
That's dangerous because using Task<T>.Result can deadlock in some cases, if the task needs to do more work in the current synchronization context before completing. You could avoid that by making your NinjaAttack method asynchronous instead:
public class MyClass
{
private readonly Task<Ninja> ninjaTask;
public MyClass(Task<Ninja> ninjaTask)
{
this.ninjaTask = ninjaTask;
}
public async Task NinjaAttack() => (await ninjaTask).Attack();
}
Depending on your context, you might want to use await ninjaTask.ConfigureAwait(false).

Event dispatching library with IoC

In the past I've built a MessageDispatcher component that scans an assembly for types decorated with certain attributes and initializes an instance of each. Then, when any object is fed to the MessageDispatcher instance, every previously initialized instance which contains a method which signature contains the type of the passed object has said method triggered with the specified parameter. For example, in a scenario like:
[Listener]
public class MyListener
{
MessageDispatcher _dispatcher; //Assigned elsewhere
[MessageListener]
public async Task DoSomething(int value)
{
var otherValue = await _dispatcher.Next<string>();
Console.WriteLine($"{value} is {otherValue}.");
}
}
The following code initializes an instance of the MyListener class, calls DoSomething and prints "7 is okay.":
var listener = new MessageDispatcher(typeof (ListenerAttribute));
listener.Dispatch(7);
listener.Dispatch("okay");
I would like to know if there are any libraries out there that are dedicated to or include a service like such. It has to be able to:
Scan assemblies and initialize types based on an attribute.
Dynamically "subscribe" to certain types
"Wait" on a value to be pumped from the dispatcher (like with the Next method in my example).
(as library recommendations is not allowed per the SO rules, here is an attempt to instead answer with an implementation)
You can get that with virtually any IoC. All they need is to be able to register services using an attribute or some other conventional way.
As for the message dispatching. Just create an interface like IMessageHandler<TMessage>. Implement it on all classes that should handle messages.
Example:
public interface IMessageHandler<TMessage>
{
void Handle(TMessage msg);
}
public class SomeService : IMessageHandler<UserCreated>
{
//[.. all other methods ..]
public void Handle(UserCreated msg)
{
// ...
}
}
To publish messages you create a dispatcher. Since you use a container you do not have to make it static. Use your container inside it (service location) to dispatch the messages. Now some peeps might say oohh no, service location is anti-pattern, buhuhuhu. Well no. Not in all cases. In this case it's an implementation details in a class with the specific purpose to identify and invoke other classes.
public interface IMessageDispatcher
{
void Dispatch<TMessage>(TMessage msg);
}
// The actual implementation differs
// depending on your choice of container.
public class ContainerBasedMessageDispatcher : IMessageDispatcher
{
Container _container;
public ContainerBasedMessageDispatcher(Container container)
{
_container = container;
}
public void Dispatch<TMessage>(TMessage message)
{
using (var scope = container.BeginLifetimeScope())
{
var handlers = scope.Resolve<IEnumerable<IMessageHandler<TMessage>>();
foreach (var handler in handlers)
{
handler.Handle(message);
}
}
}
}
The code is written directly in SO. So it might not work as-is. But hopefully it's given you an idea how to achieve what you want.
Usage:
public class UserService
{
IMessageDispatcher _dispatcher;
public UserService(IMessageDispatcher dispatcher)
{
_dispatcher = dispatcher;
}
public void Create(User user)
{
//[...]
_dispatcher.Dispatch(new UserCreated(user.Id));
}
}
this do however not dynamically allow you to subscribe on what you want. If just ignoring unwanted messages is not feasible. Then this answer is not for you.

Async load settings before static constructor

I was just finishing my new app, but I got stuck. My app is divided into 2 parts - remote and local. What I need is to register a class for interface based on some async deserialized application settings. Here is the 'idea code'
public class ViewModelLocator
{
static ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
// It can't work :(((
if(await SettingsManager.LoadSettings().EnableRemote) // <<<<<<
{
SimpleIoc.Default.Register<IMyService, MyRemoteService>();
}
else
{
SimpleIoc.Default.Register<IMyService, MyLocalService>();
}
SimpleIoc.Default.Register<MainViewModel>();
SimpleIoc.Default.Register<SomeOtherViewModel>();
}
How could I solve it? The settings are serialized in an XML file in Isolated Storage of my WinRT app. Please, can you think of any suggestions?
It sort of breaks the IoC pattern to register bindings asynchronously. You'll need to incorporate the async settings into a wrapper class. This wrapper class should be responsible for:
loading the settings
providing the actual implementation of IMyService
If IMyService has synchronous methods, then you'll probably have to change it, either to provide async versions of all the methods, or to provide a Ready property + event, so that consumers will know when it is safe to access. But if it's a service, its methods are probably already async, right?
As an illustration, let's call the wrapper class MyServiceWrapper. It will load the settings when it is first constructed, and pass through all asynchronous methods in IMyService (for example, SomeMethodAsync as below).
public interface IMyService
{
Task SomeMethodAsync(Action<bool> callback);
}
public class MyServiceWrapper : IMyService
{
private IMyService _impl = null;
private IMyService _remote, _local;
private bool _loaded = false;
private object _sync = new object();
public Task SomeMethodAsync(Action<bool> callback)
{
// first make sure the settings have been loaded
await LoadSettings();
_impl.SomeMethodAsync(callback);
}
public MyServiceWrapper(MyRemoteService remoteService, MyLocalService localService)
{
_remote = remoteService;
_local = localService;
LoadSettings();
}
private async Task<bool> LoadSettings()
{
if (_loaded)
return true;
// lock to prevent multiple threads from loading the settings
lock (_sync)
{
if (_loaded)
return true;
if(await SettingsManager.LoadSettings().EnableRemote)
_impl = _remote;
else
_impl = _local;
}
return true;
}
}
Now you can have your DI container register:
MyRemoteService -> MyRemoteService
MyLocalService -> MyLocalService
IMyService -> MyServiceWrapper

How to overload a method at run-time or other ideas in C#

Maybe overloading a method is not exactly what is necessary but this is the best i could come up with.
I have a class:
public class Worker {
private string jobType;
public Worker(string jt)
{
this.jobType = jt;
}
public void ProcessJob()
{
if(jobType.Equals("Pizza") MakePizza();
else if (jobType.Equals("Burger") MakeBurger();
}
private void MakePizza()
{
// make pizza
}
private void MakeBurger()
{
// make burger
}
}
The above is just an example of illustration. When the class is constructed, it is constructed with a specific job type, and that won't change. However it may need to perform millions of jobs, always of the same type. The ProcessJob() will be called all the time, but the caller won't know what type of worker this is. I would like to avoid running the if check every single time, there has to be a way to do that check only once and prep it.
In my case, making child classes (pizza worker, burger worker, etc.) is not an option, as in my real case, the class is large and there is only one tiny difference. Changing it will impact the whole architecture so it needs to be avoided.
Create an abstract base class, which contains common things a worker can do. Then declare derived classes for specialized workers.
public abstract class Worker
{
public abstract void ProcessJob();
}
public class PizzaWorker : Worker
{
public override void ProcessJob()
{
// Make pizza
}
}
public class BurgerWorker : Worker
{
public override void ProcessJob()
{
// Make burger
}
}
Now you can create workers of different types and let them do their job:
var workers = new List<Worker>();
workers.Add(new PizzaWorker());
workers.Add(new BurgerWorker());
foreach (Worker worker in workers) {
woker.ProcessJob();
}
This will automatically call the right implementation of ProcessJob for each type of worker.
Note: If-else-if cascades and switch statements are often an indication that the code works in a procedural rather than object-oriented way. Refactor it to be object-oriented!
You could use a delegate created when the object is constructed, this way the dispatch is done automatically:
public class Worker
{
private delegate void MakeSomething();
private MakeSomething makeWhat;
private string jobType;
public Worker(string jt)
{
this.jobType = jt;
switch (jt)
{
case "Pizza":
makeWhat = new MakeSomething(MakePizza);
break;
case "Burger":
makeWhat = new MakeSomething(MakeBurger);
break;
default:
throw new ArgumentException();
}
}
public void ProcessJob()
{
makeWhat();
}
private void MakePizza()
{
//make pizza
}
private void MakeBurger()
{
//make burger
}
}
I would still recommend to use sub classes. If you cannot inherit from Worker then create new class hierarchy that is used inside the worker. This way anyone using Worker class doesn't have to know that there are sub classes. If you really really hate sub classes or you have some other reason you don't want them you can use dictionary. It contains job type as key and Action as the method it calls. If you need more jobs just create the private method and register it in the RegisterWorkers method.
private Dictionary<string, Action> actions = new Dictionary<string, Action>();
public Worker(string jt)
{
this.jobType = jt;
this.RegisterWorkers();
}
private void RegisterWorkers
{
this.actions["Pizza"] = this.MakePizza;
this.actions["Burger"] = this.MakeBurger;
}
public void ProcessJob()
{
var action = this.actions[this.jobType];
action();
}
No, I don't think it should be avoided. Any common functionality should go in a base class. I think you need a static factory method, that returns a child class based on the string parameter.
public abstract class Worker {
public virtual void ProcessJob();
public static Worker GetWorker(string jobType) {
if(jobType.Equals("Pizza")
return new PizzaWorker();
else if (jobType.Equals("Burger")
return new BurgerWorker();
else
throw new ArgumentException();
}
// Other common functionality
protected int getFoo() {
return 42;
}
}
public class PizzaWorker : Worker {
public override void ProcessJob() {
// Make pizza
int y = getFoo() / 2;
}
}
public class BurgerWorker : Worker {
public override void ProcessJob() {
// Make burger
int x = getFoo();
}
}
So to use this:
Worker w = Worker.GetWorker("Pizza");
w.ProcessJob(); // A pizza is made.
This is exactly why there are patterns: Command, Strategy, Decorator.
I believe the command pattern is what you are looking for. First you have a basic 'command' template:
public interface IJob {
void ProcessJob();
}
Different jobs would then be performed as follows:
public class MakePizza : IJob {
// implement the interface
public void ProcessJob() {
// make a pizza
}
}
Now, you could have a JobFactory as follows:
public static class JobFactory {
public static IJob GetJob(string jobType) {
if(jobType.Equals("Pizza"){
return new MakePizza();
} else (jobType.Equals("Burger") {
return new MakeBurger();
}
// to add jobs, extend this if-else-if or convert to switch-case
}
}
Worker can now look like this:
public class Worker {
private IJob job;
public Worker(string jt) {
job = JobFactory.GetJob(jt);
}
public void ProcessJob() {
job.ProcessJob();
}
}
If you don't have access to code to make these changes, then another pattern you may want to look into is the Adapter.
You're talking about basic inheritance here. There are a couple of ways that you could do this.
Make a Base Class that is
public class Job
{
virtual void ProcessJob();
}
Then a MakePizza class
public class MakePizza : Job
{
public void ProcessJob()
{
//make Pizza
}
}
Then in your worker class instead of having a JobType as a string which will lead to all kinds of potential bugs.
public class Worker{
private Job jobType;
public Worker(Job jt){
this.jobType = jt;
}
public void ProcessJob()
{
Job.ProcessJob();
}
}
If you have to pass through a string you could simply load up the JobType through reflection, throwing a error if the type doesn't exist.
having to change other classes means you need to change code, not that you need to change architecture. the best answer is just to change the code. in the long term, the maintenance burden of having to write this in a less-than-ideal fashion will cost you more than just changing the code. use inheritance and bite the bullet on making the change now. if you have iterators that will have problems with dealing with subtypes, your iterators are doing more than being iterators, and you are better off fixing that than going forward with them. if the other classes care about what subtype of worker they are dealing with, that's a problem in and of itself that you should fix. ultimately, the dependent code should not care which type of worker it is. that's really what you are after anyway. the instance of a type that has work as its base type is still a worker and that is all the class using a worker should care about.

Categories

Resources