Exposing ILogger in a loosely coupled fashion - c#

I am the author of a C# open-source wrapper for a 3rd party service. I need to expose an ILogger facility (such as https://logging.apache.org/log4net/release/sdk/log4net.Core.ILogger.html) to log specific events and errors.
I could just go on and add a major logger such as Log4Net, but I don't want the wrapper to be tied to a specific logger.
I could just add an IoC container to easily solve this with a constructor dependecy injection but then again I don't want my wrapper to be tied to any specific IoC.
On the other hand it would be great if I could somehow expose the logging events to the consuming app (which is the one responsible for logging anyway) with the wrapper being agnostic towards its consumer.
Any thoughts on how to achieve this?

Projects will often provide their own abstraction. A default logger is bundled so things work out of the box, but you can easily configure the logging provider, as seen in ServiceStack logging and NServiceBus logging. For example:
LogManager.LogFactory = new Log4NetFactory(true);
There is also Common.Logging, which was designed to address the logging framework dependency issue. However, I have not seen it used extensively in major open source projects even though it's been around a while.

Related

Is an IoC container an overkill for a very simple framework

I am creating a library that integrates our product with another 3rd party product.
The design being used involves an interface that abstracts the core operations i'd like to integrate to our product, such that when a new 3rd party API is released, we would transparently switch to using it instead of the old one without modifying existing code.
To this end, the actual code that will return a concrete instance of the object interacting with 3rd party API needs to make a decision on to "which implementation to select".
For the simple needs, i assume an entry in the configuration file would suffice to say the fully qualified implementing class name.
Should i use an IoC container in this case, or should i use a Factory Method pattern and code it myself? (use reflection to instantiate the object, etc).
What are the pros and cons for this? Am i missing anything?
Quoting Mark Seemann:
Applications should depend on containers. Frameworks should not.
An IoC container sounds like overkill for your problem. If you have only one dependency to inject, doing it via the config file should be just fine.
Any IoC container is never overkill. You WILL eventually expand on this app if it's successful, or at the least used regularly and you will get requests to add more.
I'm a Castle user, and it's darn easy to add Castle with NuGet then just create a new WindsorContainer() in the startup and register your interfaces and class.
It's like asking if TDD is overkill to make a simple app. You should always (if you can) TDD the app, and use interfaces over concrete in your classes. IoC is too easy to setup now that you're only adding a few lines of code, so why not? it will be much harder later on if you didn't originally use an IoC container and you have intefaces and newed up classes all over your project to organize them all back into an IoC container.

Optional logging dependency for C# library?

I've been working on a library in C# and would like to offer capability for it automatically log all exceptions. Ideally, I'd like it to use log4net, thus allowing the client to configure the log however they like (i.e. they can redirect it to the EventLog or a database or what have you).
However, I would like to avoid having the logging dependency if they chose not to use the logging feature. Is this doable?
In other words, is there a way I can optionally have a log4net dependency, depending on what the client sets in config file?
The obvious answer is to use the System.Diagnostics.Trace subsystem with a custom TraceSource. That way you can set up, in the configuration file, any TraceListener you'd like, including log4net, EventLog, text files, Console, or XML files.
If you added a log4net TraceListener then the dependency would be loaded at runtime, and not compiled in. The Trace subsystem has become quite powerful since its inception, and I recommend you look into it.
You can use the tracing sub-system that is already built into .NET - it is configuration controlled.
I wouldn't add a dependency myself - simply emit messages through the tracing API - the client can decide how to log them if they so wish.
Personally I prefer the Log4Net API to that provided by System.Diagnostics.Trace.
So I have my own abstraction layer that uses a provider-model design pattern, and exposes an API similar to log4net. I can then plug in a log4net provider, but am free to replace it with a different provider (e.g. System.Diagnostics.Trace; EntLib) in the future.
The implementation is very similar to this one.
By doing this, applications have no direct dependency on the underlying logging provider, and you can easily switch to a different provider if you (or your customers) have other preferences.

Proper implementation of NLog and Prism

What would be the best way to implement NLog in my Prism / CAL WPF application. This might be an amateur question, I am a bit new to the whole Prism framework :)
I thought about putting the reference to the NLog dll in the Infrastructure module and make a wrapper singleton class e.g. MyLogger. My thinking was to be able to have the reference to 1 logger implementation somewhere in a central place that everything has reference to, and the only thing that I know of in Prism would be your Infrastructure module.
The obvious other way is to add a reference to NLog to each module but I think that would defeat the purpose of decoupling and all of that.
Any ideas would be most helpful
Regards
I would recommend something similar to your first idea, although it leverages an already existing interface in Prism.
While I'm not sure the exact method signatures available to you in NLog, you may want to consider using Prism's ILoggerFacade interface, which is typically defined in your Bootstrapper (see the StockTraderRI application for an example of how this is set up). Typically, this acts as a pass through to Microsoft's Composite Logging interface, but there's no reason why you can't use this to hook into your own logger.
A few reasons to consider this approach:
It uses the already existing ILoggerFacade interface in the Prism framework, which other developers will be familiar with
If you later decide to go to a different logging framework, you just have to replace the object behind the ILoggerFacade implementation
The other approach would be to do as you suggest: create an interface that defines a service to NLog (or expose an existing NLog interface) in your infrastructure DLL and register the implementation of that service in your bootstrapper. You can then you your dependency injection container to get a reference to the logger service in your modules. Note, however, that this really just reproduces what the ILoggerFacade interface already gives you.

What is the use of spring.net?

We are developing an application using Silverlight and WCF Services. Is using Spring.Net is beneficial for us?
>> "Is using Spring.Net is beneficial for us?"
I think the spirit of your question is really geared more towards questioning the benefit of using an IoC/DI framework versus manually managing dependencies as needed. My response will focus more on the why and why not of IoC/DI and not so much on which specific framework to use.
As Martin Fowler mentioned at a recent conference, DI allows you to separate configuration from usage. For me, thinking about DI in the light of configuration and usage as separate concerns is a great way to start asking the right questions. Is there a need for your application to have multiple configurations for your dependencies? Does your app need the ability to modify behavior by configuration? Keep in mind, this means that dependencies are resolved at runtime and typically require an XML configuration file which is nice because changes can be made without requiring a recompile of the assembly. Personally, I'm not a fan of XML-based configuration of dependencies as they end up being consumed as "magic strings". So there's the danger of introducing runtime errors if you end up misspelling a class name, etc. But if you need the ability to configure on-the-fly, this is probably the best solution today.
On the other hand, there are DI frameworks like Ninject and StructureMap that allow fluent in-code dependency definitions. You lose the ability to change definitions on-the-fly, but you get the added benefit of compile time validations, which I prefer. If all you want from a DI framework is to resolve dependencies then you could eliminate XML-based frameworks from the equation.
From a Silverlight perspective, DI can be used in various ways. The most obvious is to define the relationship of Views to ViewModels. Going deeper, however, you can define validation, and RIA context dependencies, etc. Having all of the dependencies defined in a configuration class keeps the code free from needing to know how to get/create instances and instead focus on usage. Don't forget that the container can manage the lifetime of each object instance based on your config. So if you need to share an instance of a type (e.g. Singleton, ManagedThread, etc.), this is supported by declaring the lifetime scope of each type registered with the container.
I just realized at this point I'm ranting and I apologize. Hope this helps!
Personally i'd recommend using either Castle or Unity as i've had great success with both and found them both, while different, excellent IOC frameworks.
Besides the IOC component they also provide other nifty tools (AOP in Castle, Interface interception in Unity, for example) which you will no doubt find a use for in the future, and having an IOC framework in place from the start is ALWAYS a hell of a lot easier than trying to retrofit it.
It's incredibly easy to setup and configure, although personally i'm not a huge fan of the XML config way of doing things as some of those config files can turn into a total nightmare. A lot of people will tell you that it's only worth doing if you intend to swap components in and out, but why not just do that anyway IN CASE you decide you need to do that later. it's better to have it and not use it, than not have it and need it. If you're worried about perf hit i've seen on many blog posts around the web people comparing the various IOC frameworks for their speed and unless you're creating brain surgery robots or the US Missile defence platform it won't be an issue.
A DI Framework might be of use if you want to change big chunks of your application without having to rewrite your constructors. For example, you might want to use a comet streaming service that you will expose through an interface, and later decide that you'd rather use a dedicated messenging system such as MQ or RendezVous. You will then write an adapter to Mq that respects the common facade and just change the spring config to use the Mq implementation rather than the Comet one.
But for the love of tony the pony, don't use Spring.Net to create your MVVM/MVP/MVC bindings for each and every view or you'll enter a world of pain.
DI is a great tool when used with parcimony, please don't end-up with 243 spring configuration files, for your devs' sanity.
Using an IOC container such as Spring.Net is beneficial as it will enable you to unit test parts of your UI by swapping in mocked or special test implementations of the applications interfaces. In the long run, this should make your application more maintainable for future developers.
I think if you do more in the code rather than using the markup to do bindings etc. and have a BAL/DAL DI can help there because it can inject the correct business component reference (as one example). DI has many other practical advantages, but then you have to do more in code and less in markup.

When would you use the Common Service Locator?

I've been looking at the Common Service Locator as a way of abstracting my IoC container but I've been noticing that some people are strongly against this type of this.
Do people recommend never using it? Always using it? or sometimes using it?
If sometimes, then in what situations would you use it and what situations would you not use it.
Imagine you are writing library code to be used by 3rd party developers. Your code needs to be able to create service objects that these developers provide. However you don’t know which IoC container each of your callers will be using.
The Common Service Locator lets you cope with the above without forcing a given IoC on your users.
Within your library itself you may wish to register your own classes in the IoC, now it gets a lot harder as you need to choose a IoC for your own use that will not get in the way of your callers.
I noticed that one of the arguments against using the CSL is a false one, because developers think this library is only capable of doing the Service Locator pattern. This however isn't the case, because it is easy to use it with the Dependency Injection pattern as well.
However, the CSL library was specially designed for framework designers who need to allows users to register dependencies. Because the library will be calling the CSL directly, from the framework's perspective we're talking about the SL pattern, hence its name.
As a framework designer however, taking a dependency on the CSL shouldn't be taking lightly. For usability of your framework it is normally much better to have your own DI mechanism. A very common mechanism is to set up dependencies in the configuration file. This pattern is used throughout the whole .NET framework. Almost every dependency can be replaced for another. The .NET provider pattern is built on top of this.
When you, as a framework designer, take a dependency on the CSL, it will be harder for users to use your application. Users will have to configure an IoC container and hook it up to the CSL. However, it is not possible for the framework to validate the configuration as can be done while using the .NET configuration system, which as all kind of validation support in it.
I've done some reading on the service locator concept lately. It is a way of helping to reduce coupling, but requires code coupling to the locator - not the container backing the locator, but the locator itself. It is a tradeoff, but can be beneficial in the right situation.
One situation where it can be helpful is when you have code that does not make use of DI, such as legacy code - I am in this boat now. Pulling in required objects via SL, rather than directly creating them, allows the addition of some abstraction. I see it as an intermediate step between SL and DI/IoC.
If you have library code that is in need of services and this code could be hosted in the context of a larger framework/runtime then the framework / runtime would need to provide a mechanism where you can run some custom code on startup wherein you can initialize your container and register dependencies.
A good example of where CSL can be problematic is when using it in the context of MSCRM. You can have custom business logic executed by registering plugins which the MSCRM framework executes on certain events. The problem you run into is where do you run the registration logic since there is no "startup" event that you can subscribe to for setting up your DI container. Even if you could somehow setup your DI you would need to put the CSL and the DI libraries in the GAC since that is the only way to call out to 3rd party code from a plugin (one more item to add to your deployment checklist).
In scenarios such as this you are better off having your dependencies as constructor parameters that the calling code can initialize as it sees fit( via either constructor injection or manually "newing" up the appropriate interface implementation).

Categories

Resources