Skip to content

Tag: C#

Why Service Locator is an Anti-Pattern?

Previously, we saw how we can use a Service Locator in order to prevent ‘newing‘ of objects in our code. However, everything comes with a price. Though we will talk about this in detail, but just to give you a gist of it, a service locator is an anti-pattern as it hides the class dependencies.   Commerce Application Example The example we are following is…

Using Service Locator Pattern in DI

To begin with, service locator pattern is one of the most commonly used pattern. In general, this pattern is used along with other patterns like Adapter Pattern, Observer Pattern, Dependency Injection Principles and many more. In this post, however, we will be talking about its use with dependency injection, which is one its many uses.   Introduction The service locator pattern works as a middle…

AsImplementedInterfaces – code with bad smell

While I was exploring Autofac, I found AsImplementedInterfaces quite interesting. Not only because it is useful, but also because if we are not careful with its use, we may end up with unexpected application behavior. However, it was quite difficult, to find an example which explains: what is AsImplementedInterfaces and how it helps? why code with AsImplementedInterfaces has a bad smell? And therefore, here we are, with this…

Dependency Injection using Autofac

In the previous post, we saw how we can inject dependencies without any DI container. However, in this post, we will see how DI containers help us by instantiating the dependencies and provide them whenever and wherever required.   What is a DI Container? In the example for our last post, we had to instantiate dependencies on our own, before injecting them via constructor. Consequently, as…

Null Object Pattern

Almost every method that we write, irrespective of the programming language, we always have checks like the following one: if (objectVariable == null) return; // do some work with objectVariable We end up adding so many null checks in our methods, that it gets almost hard to figure out what we are supposed to do in our method. This makes our code look ugly and hard…

Anonymous Types in C#

Generally, for an object to encapsulate some properties, the type of the object has to be defined first. On the contrary, anonymous types provide a convenient way for an object to encapsulate readonly properties without explicitly defining the type first. The type of each property is deduced by the compiler.   Creating an Anonymous Type We can create an anonymous type using a new keyword along…