Benefit of AddSingleton(S, T) instead of AddSingleton(T) - c#

What is the benefit of using services.AddSingleton<SomeService, SomeServiceImplementation>() instead of services.AddSingleton<SomeServiceImplementation>() ?
For example i've got an sample Interface
interface ISampleInterface
{
void DoSomething();
}
And a Sample-Class:
class SampleClass : ISampleInterface
{
public void DoSomething()
{
console.write("hi");
}
}
No i do services.AddSingleton<SampleClass>()
Why or when to use services.AddSingleton<ISampleInterface, SampleClass>() ?
Thanks for your help! :-)

services.AddSingleton<SampleInterface, SampleClass>() allows you to register different implementations for the same interface without modifying the rest of your code.
Change implementations with minimal effort
Suppose you have an ILogger interface and implementation that log eg to the browser's console or send the log entry to different services eg ConsoleLogger, MyServiceLogger or PrometheusLogger. If you registered only the implementation, with eg services.AddSingleton<ConsoleLogger>() you'd have to change all of your classes each time you changed a logger implementation.
You'd have to go to each page and change
#inject ConsoleLogger logger;
to
#inject MyServiceLogger logger;
Forget about specifying the logger at runtime too. You'd have to deploy the application each time you wanted to use a new logging service.
By registering the interface and a specific implementation, all of your classes can keep using ILogger<T> and never know that the implementation has changed.
Implementation selection at runtime
You could even change the implementation at runtime, based on environment variables, configuration, or any other logic you want, eg :
if (app.IsDevelopment)
{
services.AddSingleton<ILogger,ConsoleLogger>();
}
else
{
services.AddSingleton<ILogger,MyServiceLogger>();
}
Unit Testing
In unit tests you could use a null logger - in fact the Logging middleware has a NullLogger class just for this reason, in the core Abstractions package.
Or you could wrap your test framework's output methods into an ILogger implementation and use that, without modifying the code. xUnit for example uses the ITestOutputHelper interface for this. You could create an XUnitlogger that forwards calls to this interface:
public class XUnitLogger:ILogger
{
private readonly ITestOutputHelper _output;
public XUnitLogger(ITestOutputHelper output)
{
_output=output;
}
...
void Log(...)
{
_output.WriteLine(...);
}
}

Related

How to properly implement ILogger.IsEnabled() in custom logger in ASP.NET Core MVC

I am (as something of a novice) implementing my own custom logger for use in ASP.NET Core MVC apps. I have this logger working functionally in every regard. But I cheated a little so far, namely I implemented the ILogger.IsEnabled method as follows:
public bool IsEnabled(LogLevel logLevel)
{
return true;
}
Functionally, this works fine, since the framework ensures that the Log() method is only invoked if the log level is at or higher than the one specified. So the correct "things" are being logged and the lower-level "things" are not being logged as expected.
However, I also want to support the following kind of situation in my code, where _logger is typed as ILogger and is properly injected in my controller:
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("This is an expensive message to generate: " +
JsonConvert.SerializeObject(request));
}
To make this effective, my IsEnabled() method should be able to know what the log level IS for the instance of the logger that was created with my LoggerProvider, but I don't know how to get that information directly, or how to pass it properly to the injected instance of the the logger I am working with.
Complex examples and tutorials I have been able to find seem to be constructed in every case for console app types, not network app types, and so far I have been unsuccessful at figuring out how to do this through the templated Startup class in ASP.NET MVC.
What is the simplest and most effective way to stop cheating at my custom IsEnabled() method in order to avoid the unnecessary serialization (in my example) if none of the registered loggers in the injected instance are handling the Debug log level? Or do you have a favorite example or tutorial in the ASP.NET core setting you can point me to?
You can take a look at built-in loggers source code and see how they implement it.
In short, they only check that logLevel != LogLevel.None, but depending on the logger logic, you might also want to check some other configuration. For example, DebugLogger logger also checks the Debugger.IsAttached property and EventLogLogger checks the EventLogSettings.Filter (supplied via constructor).
Update
To make this effective, my IsEnabled() method should be able to know what the log level IS for the instance of the logger that was created with my LoggerProvider, but I don't know how to get that information directly, or how to pass it properly to the injected instance of the the logger I am working with.
You can create an implementation of ILoggerProvider which in turn can make use of dependency injection to get the configuration you want. If you want to use the options pattern to configure it, you must do something along the lines of:
public class MyLoggerProvider : ILoggerProvider
{
private readonly IOptions<MyLoggerOptions> _options;
public MyLoggerProvider(IOptions<MyLoggerOptions> options)
{
_options = options;
}
public ILogger CreateLogger(string name)
{
return new MyLogger(name, _options.Value);
}
}
And optionally add an extension method to make registration easier:
public static class MyLoggerExtensions
{
public static ILoggingBuilder AddMyLogger(this ILoggingBuilder builder, Action<MyLoggerOptions> configure)
{
builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<ILoggerProvider, MyLoggerProvider>());
LoggerProviderOptions.RegisterProviderOptions<MyLoggerOptions, MyLoggerProvider>(builder.Services);
builder.Services.Configure(configure);
}
}

Is there any way to validate the lifetime in DI?

I'm looking for some way to enforce the checking (runtime, of course) of the proper lifetime registration of dependency-injection services, in .Net Core or higher.
Let's say I have a stateful service like this one:
public class MyStatefulService
{
private object _state;
}
However, by mistake, I could register it with the wrong lifetime:
services.AddTransient<MyStatefulService>();
So, I won't be alerted, but the actual behavior is not what I'd expect: the service is created at every request, and the state won't be preserved.
I wonder if there is a way to reinforce this pattern. For instance, it would be nice if I could decorate the class with an attribute like this:
[Singleton]
public class MyStatefulService
{
private object _state;
}
at this point, possibily at startup or at the very first request, the framework should throw if the registration is different than AddSingleton (along its overloads).
Similarly, the subject could apply for transient-only services, which shouldn't registered as singletons.
The only solution came in my mind is rather naive, and I don't like so much:
//line of principle code
public static class MySingletonChecker
{
private static HashSet<Type> _set = new HashSet<Type>();
public static void Validate(Type type)
{
if (_set.Contains(type))
{
throw new Exception();
}
else
{
_set.Add(type);
}
}
}
public class MyStatefulService
{
public MyStatefulService()
{
MySingletonChecker.Validate(this.GetType());
}
private object _state;
}
Is there any better solution, hack or anything that helps to prevent errors?
If you want to idiot-proof your code, you can provide an extension method to IServiceCollection that registers your service exactly the way it should be.
public static void AddMyStatefulService(this IServiceCollection services)
{
services.AddSingleton<MyStatefulService>();
}
Then in your services configuration section, the developer would type:
services.AddMyStatefulService();
Here's a way like I was pointing out in the comments
Let's have some empty types:
public class ScopedService {}
public class TransientService {}
Let's have a real service that derives from one of the empty types:
public class RealService: ScopedService, IRealService {
//impl
}
And a generic registration method helper:
static void MyAddScoped<TService, TImplementation>(IServiceCollection services)
where TService : class
where TImplementation : ScopedService, TService
{
services.AddScoped<TService, TImplementation>();
}
Let's register our realservice using the helper:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
MyAddScoped<IRealService, RealService>(services);
}
RealService is a ScopedService - think of this as "how you decorate a service to insist it be added as scoped"
Suppose the developer changes the service to be a transient:
class RealService: TransientService, IRealService {
Now you get a compiler error from the helper method:
The type 'YourApplication.RealService' cannot be used as type parameter 'TImplementation' in the generic type or method 'Startup.MyAddScoped<TService, TImplementation>(IServiceCollection)'. There is no implicit reference conversion from 'WebApplication1.RealService' to 'WebApplication1.ScopedService'.
Your "one person who looks after registration" can know that the developer is indicating the service is no longer registerable as Scoped and can change it (and the build will be broken until it is changed, which is a good way of preventing accidental release of incorrect code)
Another way to validate lifetimes, is by inspecting the entire DI container in the ConfigureServices clause.
Each member of a IServiceCollection has a LifeTime property which gives you the information you're looking for: https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.servicedescriptor.lifetime?view=dotnet-plat-ext-5.0#Microsoft_Extensions_DependencyInjection_ServiceDescriptor_Lifetime
To move DI composition to the declaration of a class you could work with some self-made marker interfaces like IRegisterTransientServiceAs<T>and add it to your class like this:
public class MyStatefulService : IMyStatefulService, IRegisterSingletonServiceAs<IMyStatefulService>
Within your composition you have your own extension method that iterates through all loaded types within the application domain, searches for the given generic interface and register them with the declarated lifetime from the given interface.
Maybe this is not real DI, but as you already mentioned, mostly the lifetime of a service is baked into the code of the service itself and it happens very rarely that a specific service will be used in different project with different lifetimes. So IMHO it is okay to bake the desired lifetime into the class itself, instead of making the decision outside.

How to log NLog calls from a class library in my ASP.NET Core MVC app?

Let's pretend I have two projects.
The first one is an ASP.NET Core MVC project that relies on NLog.Extensions.Logging for its logging. This is great; I can use dependency injection on my controllers to get an ILogger instance, and the nlog.config file contains, well, my NLog config.
The second one is a class library, which the API depends on, that relies directly on NLog for its logging. It contains calls like this:
public class SampleClass
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public void DoStuff()
{
if (_failed) Logger.Error("oh no");
}
}
These classes are instantiated with some reflexive wizardry, and I can't use dependency injection to replace their logger. You can also think of them as some sort of model, which can't get instantiated at startup.
How do I get my library's logs to show up in the API's logging output? I would expect them to get caught by the nlog.config automatically, but they don't seem to be.
You don't need separate configuration file.
If your ASP.net MVC core project has nlog.config and it is successfully copied during build process then same configuration will get load when
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
Make sure you have copied file correctly. Also MinLevel properly set in configuration NLog.config.
Make sure you have .NET Core ClassLibrary ( Just to make sure it is loading successfully)
In your case too you can use Dependency Injection but it is different Story.
Here is the complete example with NLog
You need to get NLog and NLog.Web.AspnetCore Package
In Program.cs
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Trace);
}).UseNLog()
.UseStartup<Startup>();
}
Now In ClassLibrary Project Just Add Referece for NLog.
Note : Here Make sure that ILogger is from Microsoft.Extensions.Logging not from NLog.
public class Class1
{
//private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private ILogger<Class1> _logger = null;
public Class1(ILogger<Class1> logger)
{
this._logger = logger;
}
public void DoStuff()
{
var _failed = true;
if (_failed) _logger.LogError("oh no");
}
}
Now it will work without any issue as well.
Class libraries should never depend on a particular logging implementation. Instead, you should use an abstraction, referred to as a facade. The Microsoft.Extensions.Logging library is one such facade you can utilize, but there's others like Common.Logging. Regardless, the classes that need to utilize logging should be injected with this abstract logging facade. For example:
public class SampleClass
{
private readonly ILogger _logger;
public SampleClass(ILogger<SampleClass> logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public void DoStuff()
{
if (_failed) _logger.LogError("oh no");
}
}
Then, in your web application or whatever other concrete application that is utilizing your class library, that is where you actually set up your logging implementation, and register that via your DI container to injected in into your logging facade.
Long and short, your class library depends only on your logging facade, which allows it to generically call stuff like LogError. The application that uses your library sets up its actual concrete logging implementation, which will then be utilized under the hood by the facade for the logging the library does.

DI/IoC with a Singleton Logger class

We are using an in house simple Logger class for our application's logging tasks (.NET 3.5).
The logger code is pretty old, and is designed similarly to this:
public class Logger : ILogger
{
private ILogger instance;
private static ILogger Instance
{
// Initialized on first use.
get { return instance; }
}
public static void Debug(string msg)
{
instance.Debug(msg);
}
public static void Error(string msg)
{
....
}
}
The instance itself is being initialized on first usage (lazily).
This is not a Singleton according to its strict "by the book" implementation, but nonetheless, the access to this class from all calling code is a static access.
I would like, for testing purposes and for other architectural reasons, to be able to replace the internal instance with something else (inject it).
How can i achieve this easily? we are not using any IoC container at the moment, but i would not want to expose a setter to the Instance property since that would defeat the whole Singleton like design.
Any suggestions on how to come up with a solution for this?
Consider using Fakes Framework for testing purposes. You could stub the call to static method with something like this
ShimLogger.Instance = () => new LoggerMock();
In case of .net 3.5 you can use Moles Framework to stub static method call. Configuration code will look something like:
MLogger.Instance = () => new LoggerMock();
It would require to make static method Instance public, but after this configuration every call to static method will return your mocked instance.
Indeed, a setter does not sound like a good choice.
Instead, I would consider two possible approaches. First, an explcit configuration method:
public class Logger : ILogger {
public void ConfigureLogger( ILogger logger ) {
this.instance = logger;
}
}
An advantage of such approach is that the intention is clear plus you have to call this method in an explicit way.
Another option would be to allow one to pass a type of your logger in your configuration:
<appSettings>
<add key="loggerType" value="The.Type.From, Some.Assembly" />
</appSettings>
Then, in your Logger class you rewrite the initialization routine so that if the configuration parameter is present, you prefer the type provided in the configuration OVER the default type.
An advantage of such approach is that you can reconfigure the client with the configuration change with no changes to the code.
Anyway, IoC containers don't bite. Introduce one as it pays off in a long term.
I wouldn't roll your own. I use the Enterprise Library for almost all my logging needs. It works on desktop and asp.net projects. Asp.net can be a bit more problematic since you have to deal with security on the server but I've done it.
http://entlib.codeplex.com/
People also like Log4Net but I've never used it so I can't comment on it.
I would modify the code using the Logger. Instead of accessing the logger through Logger.Instance, pass in the desired instance of the logger into the object. Then in your factories and/or composition root you pass Logger.Instance as the source of the logger in your production code, and in your unit tests it is easy to use a mock logger.
public class Foo
{
private readonly ILogger logger;
public Foo(ILogger logger)
{
if (logger == null)
throw new ArgumentNullException("logger");
this.logger = logger;
}
public void Func()
{
try
{
// do something
}
catch (Exception ex)
{
// call the provided logger dependency
this.logger.WriteError(ex);
// not the static singleton property
Logger.Instance.WriteError(ex);
}
}
}
Another idea would be to make an internal setter for your Instance property and use the InternalsVisibleTo attribute to make the internal setter visible to your test assembly. Note that if the assembly that contains your logger is strong named, then you must specify the PublicKey in the InternalsVisibleTo attribute. Obviously this is most helpful (in the sense of not letting other developers accidentally - or on purpose - setting Instance to something else) if your logger lives in is own assembly or in some kind of infrastructure assembly where most development/logging is NOT taking place.

Why use singleton for application logging?

I was reading about the disadvantages of singleton patterns. A valid use of singleton suggested in many forums is the Logging application. I was wondering why this is a valid use of the pattern. Aren't we maintaing the state information in memory throughout the application?
Why not just use a function:
class Logger
{
public static void Log(string message)
{
//Append to file
}
}
To answer "why not just use a function": this code works incorrectly in multi-thread logging. If two threads try to write the same file, an exception will be thrown. And this is why it's good to use singleton for logging. In this solution, we have a thread safe singleton container, other threads push messages(logs) into the container safely. And the container(always a thread-safe queue) writes the messages/logs into a file/db/etc one by one.
It is better to declare interface:
interface ILogger
{
public void Log(string message);
}
Then implement specific type of logger
class FileLogger : ILogger
{
public void Log(string message)
{
//Append to file
}
}
class EmptyLogger : ILogger
{
public void Log(string message)
{
//Do nothing
}
}
And inject where required. You will inject EmptyLogger in tests. Using singleton will make testing harder, because you'll have to save to file in tests too. If you want to test if class makes correct log entries, you can use mock and define expectations.
About injection:
public class ClassThatUsesLogger
{
private ILogger Logger { get; set; }
public ClassThatUsesLogger(ILogger logger) { Logger = logger }
}
ClassThatUsesLogger takes FileLogger in production code:
classThatUsesLogger = new ClassThatUsesLogger(new FileLogger());
In tests it takes EmptyLogger:
classThatUsesLogger = new ClassThatUsesLogger(new EmptyLogger());
You inject different loggers in different scenarios. There are better ways to handle injections, but you'll have to do some reading.
EDIT
Remember you can still use singleton in your code, as others suggested, but you should hide its usage behind interface to loosen dependency between a class and specific implementation of logging.
I'm not sure what you are referring to when you ask about state information remaining in memory, but one reason to favour singleton over static for logging is that singleton still allows you to both
(1) program to abstractions (ILogger) and
(2) adhere to the dependency inversion principle by practicing dependency injection.
You can't inject your static logging method as a dependency (unless you want to pass something like Action<string> everywhere), but you can pass a singleton object, and you can pass different implementations like NullLogger when writing unit tests.
A singleton logger implementation allows for you to control easily how often your logging is being flushed to disk or the db. If you have multiple instances of the logger then they could all be trying to write at the same time which could cause collisions or performance issues. The singleton allows this to be managed so that you only flush to the store during quiet times and all your messages are kept in order.
In most circumstances the Singleton design pattern is not recommended, because it is a kind of Global State, hides dependencies (making APIs less obvious) and also hard to test.
Logging is not one of those circumstances. This is because logging does not affect the execution of your code. That is, as explained here: http://googletesting.blogspot.com/2008/08/root-cause-of-singletons.html :
your application does not behave any different whether or not a given
logger is enabled. The information here flows one way: From your
application into the logger.
You probably still don't want to use Singleton pattern though. Not quite at least. This is because there's no reason to force a single instance of a logger. What if you wanted to have two log files, or two loggers that behaved differently and were used for different purposes?
So all you really want for logger is to make it easily accessible from everywhere when you need it. Basically, logging is a special circumstances where the best way to go is to have it globally accessible.
The easy way is to simply have a static field in your application that contains the instance of logger:
public final static LOGGER = new Logger();
Or if your logger is created by a Factory:
public final static LOGGER = new LoggerFactory().getLogger("myLogger");
Or if your logger is created by a DI container:
public final static LOGGER = Container.getInstance("myLogger");
You could make your logger implementation be configurable, either through a config file, that you can set to "mode = test" when you are doing testing, so that the logger in those cases can behave accordingly, either not logging, or logging to the console.
public final static LOGGER = new Logger("logConfig.cfg");
You could also make the logger's behavior be configurable at runtime. So when running tests you can simply set it up as such: LOGGER.setMode("test");
Or if you don't make the static final, you can simply replace the static LOGGER with a test logger or mocked logger in the setup of your test.
Something slightly fancier you can do that is close to a Singleton pattern but not quite is:
public class Logger
{
private static Logger default;
public static getDefault()
{
if(default == null)
{
throw new RuntimeException("No default logger was specified.");
}
return default;
}
public static void setDefault(Logger logger)
{
if(default != null)
{
throw new RuntimeException("Default logger already specified.");
}
default = logger;
}
public Logger()
{
}
}
public static void main(String [] args)
{
Logger.setDefault(new Logger());
}
#Test
public void myTest()
{
Logger.setDefault(new MockedLogger());
// ... test stuff
}

Categories

Resources