C # - Global software object

Scenario

I have a non-static class that wraps around Log4Net. This is very convenient because it is connected to another application that I have, which displays the logs of various processes that occur in a variety of software that I write (so that I can see where errors occur, batch processes fail, etc.) d.).

Problem

This is good and good, but if I want to register the whole process, I have to do a number of things:

  • Create an instance of the logging object.
  • Tell it to start.
  • Register the material.
  • Tell him to stop.

This means that if the process runs outside the class, I have to get confused about going through the Logging object, around which the pain arises, and looks messy.

Question

How can I simply declare an object in such a way that it is globally accessible for all classes ... ... and make it static, itโ€™s not really an option, I donโ€™t think so.

..... It may be a waste of time, but I like the opinions.

+4
source share
3 answers

Why do you think creating "it" static is not an option? I suspect that you are mixing the ideas of a static class with a static variable that maintains a reference to an instance of a non-static class.

public class Foo { // Instantiate here, or somewhere else private static LogWrapper logWrapper = new LogWrapper(...); public static LogWrapper LogWrapper { get { return logWrapper; } } } 

Just because a class is non-static does not mean that you cannot have one instance of one of them that is available worldwide. Usually not such a good idea, but not very bad for registration.

If you go on a single-line route, you might want to read my article on implementing a singleton number in C # .

+6
source

Looks like you want a singleton .

You can create a static property that returns a single instance of your class.

+5
source

Instead of going down a static path or a Singleton path, you can explore using Injection of Dependency (DI) with the IoC Container framework . This would check your classes and separate them from the logging class.

The IoC container will handle life time management for you; by specifying the container lifetime, you can simulate Singleton without any flaws.

There is a learning curve, but it's worth it; DI has many other benefits.

EDIT: The trick is to avoid the Service Locator trap. Mark Seemann contains some good articles about this (and the book comes out).

+4
source

Source: https://habr.com/ru/post/1300769/


All Articles