Singleton Factory for parsing Messages - c#

We are working on an application to process various XML messages and load them into a datastore. One of the devs I am working with created a Singleton Factory utilizing reflection to create an instance of the appropriate message subclass. My question is around using a singleton for the factory...(Using the samething for building the SqlCommand object need to pass to DB). The factory definitely makes sense here the part I am fuzzy about is using Singleton in conjunction with the Factory.
I have read a lot of postings, stackoverlow responses, etc and it still isn't clear to me why for this scenario we would use that pattern (Singleton with factory...I would assume just use a factory pattern?).
Just trying to better understand as what I have gathered you would want to use Singleton when you want to ensure one and only one interface?

Singletons do not ensure a single interface; they ensure a single instance of an object that is accessible globally to other objects. An example of where you might want to use a singleton is when you need a counter that is accessible from anywhere in the application. In other words the state of that single object is maintained throughout the applications lifetime.
Factories on the other hand are used to create object where you do not necessarily know the exact type of class that is returned. For example, you may have a factory that returns an automobile object but the exact class that is returned might be a Volkswagen or it might be a Ferrari.
Factories are used a lot for dependency injection (DI). So in the example you give you can use a factory to return an object that interfaces with a DB, but the actual class may interface with a DB using SQL statements or maybe it is another class that uses an object-relational mapping (ORM) framework. This decouples the actual database interface/implementation from the rest of the application and allows more flexibility in changes to DB access going forward. The factory could even return a mockup of the DB access that can be used for unit testing. DI can be used to change which method is used at run-time. I would definitively recommend using Factories for these reasons.
Factories can also return singletons. So the question to ask in determining if you need a singleton is, do I need to maintain state across the application for all of the objects that will access this. An example of wanting to maintain state is that you want to keep the connection open to the database for any object that accesses this DB object for the life of the application. Not suggesting you do this but it just an example of why you may want to maintain the state information of that object for the life of the application.

Related

asp.net mvc 5 - creating instance of same class in every method in a class

Im have a question.
I have just started a job with a new company that has one "Senior developer".
In a class he is doing this (Example):
class CarController{
public Cars GetCars(){
**Connection connect = new Connection(); // Create DB connection**
//and here some fetching of the data and returning it with a HTTP Response
}
public Cars GetCar(int id){
**Connection connect = new Connection(); // Create DB connection**
//and here some fetching the car with id, returning it with a HTTP Response
}
//and this pattern continues here...
}
I cant imagine that this is a good practise to keep creating the same instance of a class in each and every method to make call to the Database??
Isn't it also bad for the memory to keep creating instances everywhere?
In my opinion here we could use the repository pattern and only give access to the database class to the class the implements the Interface.
Right now we expose the Database class to the controller and the code is tight coupled!
He says that he cannot understand the concept of the respository an why Interfaces should be used in this case.
How do you convince a senior to refactor the code and also prove to him that his coding has no good structure?
How can i explain the cons in his code above in another way?
I cant imagine that this is a good practice to keep creating the same instance of a class in each and every method to make call to the Database? Isn't it also bad for the memory to keep creating instances everywhere?
It actually IS the best practice in this case. .NET pools database connections, so creating them generally isn't an expensive process. Reusing connections, however, can cause problems.
However, you should be disposing the connection as soon as you're done with it. A handy way of doing that is with a using statement:
using(Connection connect = new Connection()) // Create DB connection
{
//and here some fetching of the data and returning it with a HTTP Response
} // the connection is closed and disposed of here.
In my opinion here we could use the repository pattern and only give access to the database class to the class the implements the Interface. Right now we expose the Database class to the controller and the code is tight coupled!
Sure, that might be an improvement, but it's orthogonal to your first question. The repository should create the connection when needed and dispose of it when done.
How do you convince a senior to refactor the code and also prove to him that his coding has no good structure?
If you've just started, you might not be able to if you approach it that way. Just remember that most people (regardless of experience) don't like others to criticize their work. Instead, offer an alternative solution and offer some reasons why it's an improvement over the current design. A pragmatic approach would be to provide a situation in which the pattern in place causes problems (unit testing is the most obvious) and illustrate why a different design would solve that problem.
Instantiating objects directly isn't always bad
Creating object instances without using an IoC container is not always bad (imagine if we used Container.Resolve every time we wanted to create a string!) If a dependency is not a volatile dependency then it may not be a great candidate for DI.
No it is not expensive
Creating and disposing database connections over and over is not expensive (they are allocated from a pool and kept open anyway) and in fact is considered best practice.
Inject a DB connection?
In the case of a database connection, that connection must be tightly handled and disposed in a quick timeframe, so there is an argument to be made not to inject it. You certainly would not want the caller (or the composition root) to instantiate the connection and then require the consumer of the connection to Dispose it; that is a violation of of two commonly-held principles:
Scope that creates an instance should also destroy it
Injected instances should have longer lifespan than the object using the injected instance
Inject a factory?
Perhaps you could inject a database connection factory, but this is a little problematic because IDBConnection doesn't contain all the members found in SqlConnection. So if you want to use DI here you'd either need to supply a concrete instance (which is sealed, by the way, so no shims) or you'd need to strip away all the SQL-only features from your implementation. Same is true of SqlCommand -- IDBCommand only has a very small subset of the properties, and none of the async methods at all.
What would it gain you?
Would it get you loose coupling? Not really. You'd have sort of a fake loose coupling, but there is an implicit logical coupling between the data access classes and the SQL server database (for example, they have a schema in common). It's not like you could replace your SqlClient with an OracleClient and expect it to work. I've seen lots of folks try it, for years; if you are still trying you haven't caught on. It doesn't work. A feature-rich database client is going to have some hard dependencies on the database platform, period.
Would it be easier to unit test? Not sure. As I noted above, you can't really write shims or stubs because the SqlConnection, SqlCommand, SqlParameter, etc. are all sealed, and all have concrete methods not found in the interfaces. so no matter what, you are still going to be stuck mocking instead of stubbing.
What is the long term plan?
Maybe the plan is to replace all that low level SQL stuff with an EF at some point in the future. If so, it would be waste of time to retrofit DI into the DAL at this point, because it would all be thrown away in the end.
My conclusion
This is a judgment call. Your colleague is entitled to make it. I would focus on other, more obvious, lower-hanging fruit for refactoring.

In IoC, what is the practice for loading an object by ID?

I've just started learning about IoC, and I understand the general use of it, but so far, the loading process from AutoFac, Ninject and Zenject seem to be based on loading an object not based on data.
In other words, ConsoleLogger is created when ILogger is requested, which does not require any special ID's, and that makes sense. However, what about when I want to load IUser for Id 4? Is there a standard IoC for handling that, or are the interfaces supposed to carry methods for loading based on Id?
For instance, am I supposed to have IUserManager, with LoadUser(int id) as a method? or is there some IoC structure for this as well?
Thanks.
[note: I did search the web for this, but my queries did not seem to pull up relevant information and the similar question search yields too many generic questions to filter]
IoC containers rules the way we link object's by dependencies, dependencies means some logic under Iterfaces, so IoC mostly works on Type level rather then Instance level.
Please note that types which has no any dependencies, interfaces as well as special scope requirements may be legally created by using "new" keyword for e.g. Data Transfer Objects (dto's).
In your case, you probably need a some kind of factory that can realize by parameters what kind of object caller is needed.
However, I'll suggest to you separate data from business logic as much is it can be separated.

Best design pattern for objects where state is important - Singleton or Static

More specifically, What's the best approach for classes where state matters, within an application which implements Dependency Injection.
Say I need access to an object that's in a particular state. For example, this object might have been initiated in a different thread, or by a process I have no control over.
A good example of an object like this that already exists in .NET is the HttpContext.
In this case, Microsoft decided to go with the Static approach, so I just say:
var currentObj = HttpContext.Current;
And this gives me a particular instance of an object without having to worry where it came from.
The problem with the Static approach is that it doesn't play very nicely with dependency injection.
The other option is to configure your certain class as a Singleton in your IoC Container. This means that you can inject it, and depending on the current IoC Container config it'll be the correct instance of the class.
However, the downfall of this approach is that the stateful importance of the object is no longer explicit in the code, it's not obvious by looking at it. With the Static class used to access and instance it's more clear that the state is important. Maybe that doesn't matter though.
So, is there a pattern that helps me out here?
Context:
For context, I'm working on an application which has many instances of a class performing IO operations. They exists within their own threads.
I want to be able to interact with those objects (background tasks) via a web interface, so a Controller. I want to be able to interrogate them, and manipulate them etc.
Update:
Sorry, I think my use of the term "stateful" is a bit misleading. let me explain some thing:
"state" is probably the wrong word. I mean communicating with an object whereby I don't have control over it's lifecycle.
It is funny that I use "stateful" when talking about static classes. That's why I gave the HttpContext example, as that exactly what it does. The Current property gets you a very specific instance, not any new instance.
When I say that static doesn't play nice with DI, I meant, you can't inject Static classes. I could create a wrapper, yes, but I'm just pushing the problem elsewhere no?
I should have been more clear about my definition of Singleton. I meant a Singleton lifestyle, as defined in an IoC Container.
I always prefer Singleton over static. In fact, I almost never use statics in my own classes.
True singletons and static classes are both very difficult to write automated tests against. Do you mean a single instance looked up at runtime? That would make sense to me but I don't know the right construct to use in C#. The analog in Java is JNDI.
Neither or both. Presuming the stateful dependency is thread-safe the better approach is to build at least a basic layer of abstraction around said dependency then inject said abstraction into your classes. Singleton vs static becomes pretty immaterial then.

Pattern for objects initialization at startup

I'm building an application and as time goes on, I have more and more objects to initialize at startup. Moveover, some of the newer objects depend on others so I'm getting some kind of spaggetti initialization where objects are created then passed to other constructors. I'm suspecting that I'm getting it wrong.
For example I have a WinForm which accepts a "Controller" class and 2 events. The controller needs to be told about the existence of a DataGridView from the WinForm so it has a method
Controller::SetDataGridReference(DataGridView^ dgv)
Is there a general method of instanciating objects at startup then referencing those objects to each another?
I've been told that putting all the required classes as constructor parameters is a good practice but frankly, I don't see how I can do that here.
I don't really think that the language matters
This looks like a textbook case for using dependency injection (DI). It will certainly help with your spaghetti code and can even assist with unit testing. If you want to make a gradual migration towards DI you might want to consider refactoring the objects with similar relationships and using a few sets of factory classes that can handle all the boilerplate chain intialization as well as centralizing where all that takes place in your code base.
I can recommend Google Guice as a good DI framework for Java. Even if you arent using Java it is a good DI model to compare against other language's DI frameworks
Two patterns pop into mind as possibly appropriate depending on the specifics of your problem:
Abstract Factory Pattern. This can work with or without the Dependency Injection approach suggested by #Scanningcrew.
Mediator Pattern. Construct a mediator. Pass the mediator into the constructor of each object. Have each object register with the mediator. Then the objects don't need to know about each other explicitly. This works well when you have a set number of objects interacting with each other.
Use the Controller Design Pattern.
That is, create a SINGLE class that will be instanced on program initialization, called Controller. On the constructor of that class, create all other objects. Whatever object that needs any other objects should receive said object as a parameter on its constructor. No one, no absolutely any other object should create anything on their constructor. Pass everything as parameters on their constructors. Also, on the Controller class destructor/dispose call all objects destructor/dispose method in reverse order. This won't reduce your code, but it will make if far better to understand and debug later on.
Dependency Injection should help here: at application boot you can choice to build the complete (or sort of) graph of objects. The entry point of your application will instantiate the DI container of your choice, the you just request the root object.
For example Google Guice comes with a very nice Object grapher.
For the objects interaction, I would go for a Mediator. Check out this definition:
"Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently."
For the instantiation, I would consider the Dependency Injection. Remember that you can freely use and mix design patterns to achieve your goals.

What is a .NET proxy object in the Inversion of Control / Aspect-Oriented sense?

What is a proxy object in the Inversion of Control / Aspect-Oriented sense?
Any good articles on what a proxy object is ?
Why you would want to use one ?
And how to write one in C# ?
In general, a Proxy object is an object (instance of a class) that exposes the exact same public interface as a "real class" but simply forwards all calls made to it's members to the other real class. Proxy objects are used for a variety of reasons...
One purpose is to "pretend" to be the real class so a client component (or object) can "believe" it's talking to the "real" object, but inside the proxy, other stuff, (like logging, transactional support, etc.) is being done at the same time... Secondly, a proxy can be very cheap in comparson to the real object,. and often is used so that the real objects can be conserved (turned off or released to a pool to be used by other clients) when the client is not using them... The proxy stays "alive" and the client thinks it still has a connection to the real object, but whenever it "calls" the object, it is actually calling the proxy, which goes and gets another real object just to handle the call, and then releases the real object when the call is done.
As to Inversion of Control (IOC).. That refers to a common pattern (also referred to as Dependency Injection), where dependant objects inside of a class are "injected" into an instance of the class, from client code, to control which version of a dependant object the instance will use... IOC can be used to inject a "Proxy" object into a class where it thinks it is using the real object... The phrase Inversion of Control refers to the fact that when using this pattern, the decision as to which actual implementation is called is no longer under the control of the class making the call, but to the client of that class, when it injects an instance of a dependant object into the class to be used for this call.
Generally the term IOC is used with what is called an IOC Container, which is a class specifically designed to be responsible for creating instances of dependant classes based on loosely coupled information about those classes (Types) which it gets from some source other than hard-wired dependencies (most often, from some kind of configuration file). Generally, when you use an IOC container, you create an instance of it when the application starts, and then (by reading config data or whatever), you "register" each of the classes (types) that the IOC container will be responsible for, with a key value. The key is often the abstract type or interface that all instances of this registration must implement). Then, in the normal operations of your application, where you might otherwise have new'd up an instance of one of these types, you call the IOC Container, and ask it for an instance instead, using the abstract type/Interface as the key. The IOC container then uses reflection or dynamic loading, (or whatever), to create an instance of whatever type has been "registered" with that key. In this way, simply by changing configuration data, you can control the actual types used by the application, changing them in one environment or deployment location from those used in another.
A very good resource about this is the old "Gang of Four" design patterns book. This book is very usefull for anyone developing object-oriented software.
I'm personally using proxy objects for lazy loading with NHibernate. I don't use proxies with inversion of control because I resolve interfaced types only with my IoC.
Charles Bretana's explanation is very good.
I can't imagine the relation between proxy and AoP. Could someone explain that here?

Categories

Resources