Quartz .NET job execution to call existing class method - c#

I have an existing C# ASP.NET application with a user interface and various buttons to initiate actions. The actions make synchronous method calls on a class which is a singleton and I'll call this class ServiceLayer. This layer also initializes a data model.
I want to schedule some of the actions from the UI to occur at certain times of day. I believe Quartz.NET provides all the necessary features I need to do this. I can successfully call methods on the singleton class ServiceLayer from the Execute(IJobExecutionContext context) of each Job class (i.e. classes which implement the IJob interface). However, I don't like using this approach for a few reasons:
Difficult to unit-test (e.g. I have to ensure the singleton is initialized before I can do anything)
Scaling up if many jobs are called
Thread safety issues associated with calling multiple methods on the singleton class at the same time.
My question is what is the best design pattern to handle this case instead of calling methods on a singleton directly? I believe I need to make use of the JobDataMap somehow but I'm not sure how. Should I be looking at a producer-consumer or a queuing approach?

You might want to consider implementing a custom job factory that injects your service layer object into the job. There are already implementations of custom factories for the most popular DI containers out there, so you could go with one of those or build your own. This would allow you to pass a reference to your service layer object each time you create a job and should help with unit testing. It would also resolve the singleton issue.
As far as scaling up is concerned, you could use the JobDataMap to pass in things like connection strings or server names, allowing you to load balance or distribute work across your servers.
Here are some posts describing the custom job factory approach if you end up going down that path.

Related

Doubts about concurrency in injected services in ASP.NET Core

I have a service injected into the ASP.NET dotnet framework service container. I inject this service as a Singleton, and its function is to maintain several data structures (Dictionay, List, Queue) in memory.
The service is perfectly accessible from the controllers, and my doubts are due to the lack of knowledge of the internal workings of ASP.NET.
My questions are:
Should I worry about creating the Singleton (thread safe) or does the container take care of it?
Are accesses to service methods enqueued in a single thread?, or can they be called concurrently? I ask to know if I have to use Concurrent Collections instead of the Generic ones.
Would it be convenient to make the methods asynchronous?
I accept any suggestion, and examples.
Thanks in advance.

Where should be placed classes with long living connections in ASP.NET Core?

Right now I am using a class with socket as a property, but I would like to know how to handle this case in a better way. The class is registered as singleton in DI and the Connect method on the socket is called in the constructor.
You can use an IHostedService
They were designed as the primary means to run long running tasks in the background.
Basically what you need to do is create a class that holds your connections, implementing IHostedService. (If you are .NET Core 2.1+ you can do that easily by deriving from BackgroundService and overriding ExecuteAsync.
Then you simply register your class as a singleton at startup (services.AddSingleton<IHostedService, YourHostedService>()), and the framework will automatically recognize it and manage starting & stopping for you.
There are two a few great advantages of this:
You don't have to worry (that much) about threading, the host will handle scheduling your task.
The framework will handle startup and graceful shutdown for you. It all works the way you already know: Using a CancellationToken with a configurable timeout.
As the class is registered as a regular singleton via the IoC container, you can access it via DI just like any other class. (Of course then you need to register it using another interface as well not just as an IHostedService). This allows you to call methods on your socket-manager from your controllers, etc.
Here are my two go to tutorials on hosted services, but you can find others as well:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.2
https://learn.microsoft.com/en-us/dotnet/standard/microservices-architecture/multi-container-microservice-net-applications/background-tasks-with-ihostedservice
One good technique would be to create an extension method such as UseMySocket targeting the IWebHostBuilder type. You can use this in the CreateWebHostBuilder method of your Program class. Keep in mind that you have to implement it in a way that does not block the current thread. For example:
WebHost.CreateDefaultBuilder(args)
.UseMySocket()
.UseStartup<Startup>();
Another technique would be to create a singleton type for the socket followed by instantiating it and injecting it into the service collection in the ConfigureServices method in the Startup class.

Singleton-like behavior with Dependency Injection

After doing some research on MEF I came across the CreationPolicy.Shared property which according to MSDN:
Specifies that a single shared instance of the associated
ComposablePart will be created by the CompositionContainer and shared
by all requestors.
Sounds good as long as I always ensure that one and only one container ever accesses the class that I export with this policy. So how do I go about ensuring that only one container ever accesses my exported type? Here is my scenario:
I have a Windows service that needs to tap into a singleton-like class for some in-memory data. The data is non-persistent so I want it to be freshly created whenever the service starts up but it serves no purpose once the service is stopped. Multiple threads in my service will need to read and write to this object in a thread-safe fashion so my initial plan was to inherit from ConcurrentDictionary to ensure thread safe operations against it.
The threads that will be tapping into this class all inherit from a single abstract base class, so is there a way to have this class (and only this class) import it from MEF and have this work the way I want?
thanks for any tips you may have, I'm newish to MEF so I'm still learning the ins and outs
If it absolutely must be a singleton amongst different containers, you could use a private constructor and expose a static Instance property, as if it were a "classic" non-container-managed singleton. Then in the composition root, use ComposeExportedValue to register it with the container:
container.ComposeExportedValue(MySingleton.Instance);
You could always use the Lazy type since it blocks other threads as described in this blog post: http://geekswithblogs.net/BlackRabbitCoder/archive/2010/05/19/c-system.lazylttgt-and-the-singleton-design-pattern.aspx

Why use services (IServiceProvider)?

I'm coming to this question from exploring the XNA framework, but I'd like a general understanding.
ISomeService someService = (ISomeService)Game.GetServices(typeof(ISomeService));
and then we do something with whatever functions/properties are in the interface:
someService.DoSomething(); // let's say not a static method but doesn't matter
I'm trying to figure out why this kind of implementation is any better than:
myObject = InstanceFromComponentThatWouldProvideTheService();
myObject.DoSomething();
When you use the services way to get your interface, you're really just getting an instance of the component that provides the service anyway. Right? You can't have an interface "instance". And there's only one class that can be the provider of a service. So all you really have is an instance of your component class, with the only difference being that you only have access to a subset of the component object (whatever subset is in the interface).
How is this any different from just having public and private methods and properties? In other words, the public methods/properties of the component is the "interface", and we can stop with all this roundaboutness. You can still change how you implement that "interface" without breaking anything (until you change the method signature, but that would break the services implementation too).
And there is going to be a 1-to-1 relationship between the component and the service anyway (more than one class can't register to be a provider of the service), and I can't see a class being a provider of more than one service (srp and all that).
So I guess I'm trying to figure out what problem this kind of framework is meant to solve. What am I missing?
Allow me to explain it via an example from XNA itself:
The ContentManager constructor takes a IServiceProvider. It then uses that IServiceProvider to get a IGraphicsDeviceService, which it in turn uses to get a GraphicsDevice onto which it loads things like textures, effects, etc.
It cannot take a Game - because that class is entirely optional (and is in a dependent assembly). It cannot take a GraphicsDeviceManager (the commonly used implementation of IGraphicsDeviceService) because that, like Game is an optional helper class for setting up the GraphicsDevice.
It can't take a GraphicsDevice directly, because you may be creating a ContentManager before the GraphicsDevice is created (this is exactly what the default Game class does). So it takes a service that it can retrieve a graphics device from later.
Now here is the real kicker: It could take a IGraphicsDeviceService and use that directly. BUT: what if at some time in the future the XNA team adds (for example) an AudioDevice class that some content types depend on? Then you'd have to modify the method signature of the ContentManager constructor to take an IAudioDeviceService or something - which will break third-party code. By having a service provider you avoid this issue.
In fact - you don't have to wait for the XNA team to add new content types requiring common resources: When you write a custom ContentTypeReader you can get access to the IServiceProvider from the content manager and query it for whatever service you like - even your own! This way your custom content types can use the same mechanism as the first-class XNA graphics types use, without the XNA code having to know about them or the services they require.
(Conversely, if you never load graphics types with your ContentManager, then you never have to provide it with a graphics device service.)
This is, of course, all well and good for a library like XNA, which needs to be updatable without breaking third-party code. Especially for something like ContentManager that is extendible by third parties.
However: I see lots of people running around using DrawableGameComponent, finding that you can't get a shared SpriteBatch into it easily, and so creating some kind of sprite-batch-service to pass that around. This is a lot more complication than you need for a game which generally has no versioning, assembly-dependency, or third-party extensibility requirements to worry about. Just because Game.Services exists, doesn't mean you have to use it! If you can pass things (like a SpriteBatch instance) around directly - just do that - it's much simpler and more obvious.
See http://en.wikipedia.org/wiki/Dependency_inversion_principle (and it's links) for a good start as to the architectural principles behind it
Interfaces are clearer and easier to mock.
That can be important, depending on your unit test policy.
Using a service provider is also a way of better controlling what portions of your code have access to certain other portions of your code. Similarly to passing an object through your code, you can pass an IServiceProvider implementation through the code to specific modules. This would allow for those modules to access certain services that are accessible through the service provider.
You can have many classes implement the IServiceProvider interface, each of which could provide access to one or more services - they are not restricted to returning a single instance (whether that be to themselves or another object).
For example, a use may be to have an IServiceProvider that contains services for keyboard handling, mouse handling and AI algorithms. Passing this interface to different modules or managers within your code will allow those modules or managers to retrieve the services they require (such as an EnemyManager needing access to the AI service).

In what circumstances should I use a Singleton class?

Closed as exact duplicate of this question. But reopened, as the other Singleton questions are for general use and not use for DB access
I was thinking of making an internal data access class a Singleton but couldn't convince myself on the choice mainly because the class has no state except for local variables in its methods.
What is the purpose of designing such classes to be Singletons after all?
Is it warranting sequential access to the database which is not convincing since most modern databases could handle concurrency well?
Is it the ability to use a single connection repeatedly which could be taken care of through connection pooling?
Or Is it saving memory by running a single instance?
Please enlighten me on this one.
I've found that the singleton pattern is appropriate for a class that:
Has no state
Is full of basic "Service Members"
Has to tightly control its resources.
An example of this would be a data access class.
You would have methods that take in parameters, and return say, a DataReader, but you don't manipulate the state of the reader in the singleton, You just get it, and return it.
At the same time, you can take logic that could be spread among your project (for data access) and integrate it into a single class that manages its resources (database connections) properly, regardless of who is calling it.
All that said, Singleton was invented prior to the .NET concept of fully static classes, so I am on the fence on if you should go one way or or the other. In fact, that is an excellent question to ask.
From "Design Patterns: Elements Of Reusable Object-Oriented Software":
It's important for some classes to
ahve exactly one instance. Although
there can be many printers in a
system, there should only be one
printer spooler. There should only be
one file system and one window
manager. ...
Use the Singleton pattern when:
there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point
the sole instance should be extensible by subclassing and clients should be able to use an extended instance without modifying their code
Generally speaking, in web development, the only things that should actually implement Singleton pattern are in the web framework itself; all the code you write in your app (generally speaking) should assume concurrency, and rely on something like a database or session state to implement global (cross-user) behaviors.
You probably wouldn't want to use a Singleton for the circumstances you describe. Having all connections to a DB go via a single instance of a DBD/DBI type class would seriously throttle your request throughput performance.
The Singleton is a useful Design Pattern for allowing only one instance of your class. The Singleton's purpose is to control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields.
Source: java.sun.com
using a singleton here doesn't really give you anything, but limits flexibility
you WANT concurrency or you won't scale
worrying about connections and memory here is a premature optimization
As one example, object factories are very often good candidates to be singletons.
If a class has no state, there's no point in making it a singleton; all well-behaved languages will only create, at most, a single pointer to the vector table (or equivalent structure) for dispatching the methods.
If there is instance state that can vary among instances of the class, then a singleton pattern won't work; you need more than one instance.
It follows, then, by exhaustion, that the only cases in which Singleton should be used is when there is state that must be shared among all accessors, and only state that must be shared among all accessors.
There are several things that can lead to something like a singleton:
the Factory pattern: you construct
and return an object, using some
shared state.
Resource pools: you have a shared
table of some limited resources,
like database connections, that you
must manage among a large group of
users. (The bumpo version is where
there is one DB connection held by
a singleton.)
Concurrency control of an external
resource; a semaphore is generally
going to be a variant of singleton,
because P/V operations must
atomically modify a shared counter.
The Singleton pattern has lost a lot of its shine in recent years, mostly due to the rise of unit testing.
Singletons can make unit testing very difficult- if you can only ever create one instance, how can you write tests that require "fresh" instances of the object under test? If one test modifies that singleton in some way, any further tests against that same object aren't really starting with a clean slate.
Singletons are also problematic because they're effectively global variables. We had a threading issue a few weeks back at my office due to a Singleton global that was being modified from various threads; the developer was blinded by the use of a sanctioned "Pattern", not realizing that what he was really creating was a global variable.
Another problem is that it can be pathologically difficult to create true singletons in certain situations. In Java for example, it's possible to create multiple instances of your "singleton" if you do not properly implement the readResolve() method for Serializable classes.
Rather than creating a Singleton, consider providing a static factory method that returns an instance; this at least gives you the ability to change your mind down the road without breaking your API.
Josh Bloch has a good discussion of this in Effective Java.
You have a repository layer that you want created once, and that reference used everywhere else.
If you go with a standard singleton, there is a bad side effect. You basically kill testability. All code is tightly couple to the singleton instance. Now you cannot test any code without hitting the database (which greatly complicates unit testing).
My advice:
Find an IOC that you like and integrate it into your application (StructureMap, Unity, Spring.Net, Castle Windsor, Autofac, Ninject...pick one).
Implement an interface for you repository.
Tell the IOC to treat the repository as a singleton, and to return it when code is asking for the repository by the interface.
Learn about dependency injection.
This is a lot of work for a simple question. But you will be better off.
with c#, I would say that a singleton is rarely appropriate. Most uses for a singleton are better resolved with a static class. Being mindful of thread safety is extremely important though with anything static. For database access, you probably don't want a single connection, as mentioned above. Your best bet is to create a connection, and use the built in pooling. You can create a static method that returns a fresh connection to reduce code, if you like. However an ORM pattern/framework may be better still.
In c# 3.5 extension methods may be more appropriate than a static class.

Categories