Seemann's DI Azure Table Data Access - c#

In book "Dependency Injection in .Net" by Mark Seemann, in second chapter, is analysis of some badly written 3-layer asp.net application. The main point is: application fails because the lowest layer, data access, can not be converted from SQL with Entity Framework to Azure with no-SQL database. Here is exact quotation:
To enable the e-commerce application as a cloud application, the Data Access library
must be replaced with a module that uses the Table Storage Service. Is this possible?
From the dependency graph in figure 2.10, we already know that both User Interface and Domain libraries depend on the Entity Framework-based Data Access library.
If we try to remove the Data Access library, the solution will no longer compile,
because a required DEPENDENCY is missing.
In a big application with dozens of modules, we could also try to remove those
modules that don’t compile to see what would be left. In the case of Mary’s application, it’s evident that we’d have to remove all modules, leaving nothing behind.
Although it would be possible to develop an Azure Table Data Access
library that mimics the API exposed by the original Data Access
library, there’s no way we could inject it into the application.
Graph 2.10:
My question is - why module that is imitating previous behavior can not be injected into application, and what that really mean? Is it related to Azure specifics? I have not been working much with no-sql database before.

Essentialy, what he means is that your UI code is directly dependent on the code in the Data Access library. An example of how this might be used in the UI-layer:
public class SomeController : Controller
{
[Route("someRoute")]
[HttpGet]
public ViewResult SomeRoute()
{
// Here we're using the data component directly
var dataComponent = new DataAccessLayer.DataComponent();
return View(dataComponent.GetSomeData());
}
}
If we want to swap out the DataAccess-library it means we would have to go into all our controllers and change the code to use the new component (unless we create exactly the same class names in the same namespaces, but that's unlikely).
On the other hand, we could also write the controller like this:
public class SomeController : Controller
{
IDataComponent _dataComponent;
public SomeController(IDataComponent dataComponent)
{
_dataComponent = dataComponent;
}
[Route("someRoute")]
[HttpGet]
public ViewResult SomeRoute()
{
// Now we're using the interface that was injected
return View(_dataComponent.GetSomeData());
}
}
By defining the class like this, we can externally specify which concrete class that implements the IDataComponent interface should be injected into the constructor. This allows us to "wire" our application externally. We're injecting a concrete class into a class.
Dependency Injection is one way to make it easier to "program against an interface, not a concrete class" .
The example Mark Seemann gives relates to databases vs Azure Table Storage, but it's just that, an example. This is not related to NoSql (or storage mechanisms in general). The same principles apply for everything that depends on other classes (generally service-type classes).
EDIT after comments:
It's indeed true that you could just modify the internals of the DataComponent (or repository if that's what you're using).
However, using DI (and programming against an interface in general) gives you more options:
You could have various implementations at the same time and inject a different implementation depending on which controller it is (for example)
You could reuse the same instance in all your controllers by specifying the lifecycle in the registration (probably not usable in this case)
For testing purposes, you could inject a different implementation into the controller (such as a mock, which you can test for invocations)

Related

Access HttpContext in constructor for fake DI

I am working on an asp.net mvc application that does not have DI or unit testing yet. So I started to restructure the application to have unit tests by spliting the application into 3 layers: Controllers - Services - DataAccess.
Some of the controllers were using the Session and the Cookies to store and retrieve values. So I create an interface and a class that deals with saving and retrieving values from Session and Cookies.
I did this only by using unit testing and never run the application.
Since the application did not had DI I created on the contructor of the controller the ContextService by giving as an input parameter the HttpContext of the Controller.
However when I run the application the values were not retrieved or saved in the Session or Cookies. It seems that the HttpContext is null on contructor.
Question 1:
How should I deal with my ContextService. Should it use the static property HttpContext.Current in order to access the session and cookies (how will it be unit tested) or ...?
Question 2:
If you know another solution how should it be adapt in order to have also DI in the future.
I created on the contructor of the controller the ContextService by giving as an input parameter the HttpContext of the Controller.
By passing the HttpContext from the controller to the service, you make the controller responsible of the creation of that service. This tightly couples the controller with the service, while loose coupling is the goal.
hould it use the static property HttpContext.Current in order to access the session and cookies
how will it be unit tested
It won't. This is an important reason why we create abstractions. Some parts in our system can't be unit tested and we want to be able to replace them with fake implementations that we use under test.
The trick, however, is to make the replaced part as small as possible, and preferably don't mix it with business logic, since replacing that will also mean you won't be testing that logic.
You should hide access to the HttpContext.Current behind an abstraction. But when you do that, make sure that you define the abstraction in a way that suits your application best. For instance, take a close look at what it is that your ContextService wants. Does it really want to access cookies? Probably not. Or does it want to the name or ID of the currently logged in user? That's more likely. So you should model your abstractions around that.
As an example, define an abstraction that allows application code to access information about the logged in user using a IUserContext:
public interface IUserContext
{
string UserName { get; }
}
One possible implementation of this abstraction is one that retrieves this information from an HTTP cookie:
public class CookieUserContext : IUserContext
{
public string UserName => HttpContext.Current.Cookies["name"];
}
But you can easily imagine other implementations, for instance when that same application code needs to run outside the context of a web request, for instance as part of a background operation, or an isolated Windows service application. This is another important reason to introduce abstractions—whenever the same code needs to be able to run in different environments.
If you're interested, the book Dependency Injection in .NET, by Mark Seemann, goes into great detail about these kinds of patterns and principles, such as reasons for applying DI, preventing tight coupling. The second edition of this book, by Seemann and myself, even goes into more detail about the things you are struggling with, such as preventing leaky abstractions, how to separate behavior into classes, and designing applications using the SOLID principles. The book's homepage contains a download link for the first chapter, which is free to download.

The Dependency Inversion Principle with .NET Framework classes

I'm trying to understand SOLID principles, in particular The Dependency Inversion Principle.
In this is SO answer it is explained very well.
I think I have understood that I can't create any instance of a class inside my class. Is it right?
But if I have to save to disk some content, can I create an instance of System.IO.File or do I have to inject it?
I don't understand where is the limit, if I can't instance my own classes or if I can't either instance .NET Framework classes (or whatever other framework).
UPDATE:
I think File is a bad example because is declared as static.
By the way, does this principle apply to static classes?
The S of SOLID stands for SRP (Single Responsibility Principle). You won't violate it by using System.IO.File inside a class directly, once you keep that class with one single responsibility.
It's a good idea trying to abstract the purpose behind using System.IO.File. Let's suppose you need it to generate a log. Then you would probably do something like:
public interface IMyLogger
{
void GenerateLog(IEnumerable<string> content);
}
public class FileLogger: IMyLogger
{
public void GenerateLog(IEnumerable<string> content)
{
System.IO.File.WriteAllLines("C:/Log", content);
}
}
Maybe it's not just a log, it's something more important, like generating a file so other system/app (even external) read it and do some job.
If you are trying to use a DDD approach, the interface could belong to your domain, and the implementation could belong in the application. Then you register your interface as a service and inject it.
The class which needs an IMyLogger actually doesn't need to know how is the log being generated, it just needs the job to be done.
You can apply the same idea when you need to send an email inside some business logic in your domain. Instead of making a connection to an Exchange inside your domain directly, create an interface INotifier and a MailNotifier implementing it to be injected.
Somewhere down the chain of dependencies you will need to use the concrete class directly. Even if you use a DI framework like Ninject, the framework itself will create an instance of the concrete type, so it will not be injected into the framework (which wouldn't make sense, of course).
You can only abstract something away to a certain level. It will vary from project to project - you have to ask yourself if you need another level of abstraction (be it for modularity, unit testing etc.). I think this is very important - you want to be pragmatic, not create layers upon layers of abstractions just for the sake of it.
By the way, does this principle apply to static classes?
Yes, it does. But with static classes you have to introduce a wrapper, which will delegate calls to the static class, because a static class cannot implement interfaces.
There is no point in applying a principle just for the sake of it. Think in a pragmatic way.
If you want to unit-test a method that uses hard coded file accesses, your unit tests will access these files. This is usually not desired as you must set up or clean up these files. To avoid this, you would inject a service which wraps these file accesses. This allows you to replace the real service with a fake one during the unit tests. This fake service can provide hard coded test data for read accesses and dump written data to memory for later analysis or simply do nothing. Btw.: NSubstitute can create fake services at runtime easily.
The injection of services allows you to achieve Unit Test Isolation. E.g. you can test some logic without depending on correct file handling or database accesses or the correct functioning of other services. Injecting a service is just one way to do it. You could also just specify a method parameter as IEnumerable<string> with the content of the file instead. Events can also be used for decoupling. Instead of writing to a log, you could raise a log event.
Most DI frameworks allow you to specify the lifetime of objects. One of these options is Singleton, which means that the DI container will always return the same instance of a requested service. This allows you to wrap static classes in a service that behaves statically.

How to handle layer specific Dependency Injection in a reusable dll with ninject?

We use ninject as our DI solution. How do I create a self sustaining class library dll with its own internal IOC. Basically I have created a service that does something and I want to register the bindings in the dll and just hand it to other people. I don't want them to care about any binding in my dll.
In the dll:
public class FirstService : IFirstService
{
public FirstService(ISecondService secondService, IThirdService thirdService)
{
//Saves locally
}
//Does stuff with second and third services
}
What the end user does:
public class ThirdService : IThirdService
{
//Create the actual implementation of this
}
What I want inside the dll:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IFirstService>.To<FirstService>();
kernel.Bind<ISecondService>.To<SecondService>();
}
I don't think I want to use IKernel here though, due to possible memory leakage.
There are 4 basic design approaches to DLLs that are commonly in use:
An application layer.
A plug-in.
A library.
A framework.
It sounds like you have one of the last 2, but it is not possible to tell based on your question which prototype you are referring to.
For an application layer, you would typically compose the components inside of the application, in the composition root, as close to the point of entry of the main executable application as possible.
For a plugin, it would typically have its own internal composition root that is fired by some method or event of the application it is plugging into (based on that application's composition root). This is sometimes facilitated by modules in DI containers.
A library would typically not have any internal composition, but would provide an API (sometimes implemented as a fluent builder) that makes it easy for the client application to compose the pieces together. See this post for a couple of ideas about how to do that.
A framework would need to have 1 or more explicit extension points for the application to integrate into. Think of how MVC controllers work. There is an internal scanning implementation that by default can instantiate any object that implements a certain interface. There is also an abstract factory that can be used to inject dependencies if the default constructor is not available (in MVC, that is IControllerFactory). See this post for more information about how to make a DI friendly framework.

Load different assembly or module for different client

i have developed a web application in .net 4.5, now a customer ask me a customization for some module of application (for example a different implementation of invoices) .
My question is can i "intercept" my customer for load customized assembly and load different assembly for general customer?
can i do it simply by reflection?
The key idea is to design the software the way its parts can be easily replaced. You should have separated your solution into multiple projects, so that you can quickly swap different implementations of your interfaces.
Furthermore, there's a thing called Dependency Injection, which basically means you can inject a different implementation depending on your needs either during a runtime or using a config file for instance. For the ease of use there are nice frameworks already prepared for you, like Ninject or Unity.
The application needs to have a solid architecture to support such possibilities. Maybe if you've provided more information about your system, I could have been more specific, but I believe doing some research on dependency injection will give you a good start.
Yes, you can. You can load an assembly from file, like this
var asmbly = System.Reflection.Assembly.LoadFrom(path);
And then use Reflection to load types.
There are several ways you can achieve this pluggability. One way is to extract the interface of the "module" and code your "module client" agains that interface, decoupling the concrete implementation from your "client" code. Then, at run time look inside the assempbly, load the type that implements said interface and inject into "module client".
I am pasting here some code I've written as a proof of concept for exacly that type of run-time loading of "modules" (this is MVC 3):
// "Module User" was decoupled from "module", by coding it against module's interface:
public class CustomerController : Controller
{
private ICustomerRepository _customerRepository;
// dependency injection constructor
public CustomerController(
...
ICustomerRepository customerRepository,
...)
{
_customerRepository = customerRepository;
}
public ActionResult Details(Nullable<Guid> id)
{
Customer c = _customerRepository.GetByKey(id.Value.ToString());
...
}
...
}
At run time:
// I first load the assembly
System.Reflection.Assembly dal = System.Reflection.Assembly.LoadFrom(System.IO.Path.Combine(pBinPath, pDALAssemblyName));
// I then look for types implementing ICustomerRepository
var addressRepositoryContract = typeof(QSysCamperCore.Domain.IAddressRepository);
var addressRepositoryImplementation = dal.GetTypes()
.First(p => addressRepositoryContract.IsAssignableFrom(p));
...
Note, that this type of programming requires a little more permissions - I am already a few years "rusty" on this code, but I remember issues with the trust level and, of course, file system access has to be considered.
There are frameworks that aid such application style. This is again a few years old, but there used to be so-called "Composite Application Block" on Microsoft's Patterns and Practices site, which was the base of two frameworks - Smart Cliet Softweare Factory and its web equivavelnt - Web Client Software Factory. They were a little heavier to stand up, but provided gread skeleton for such modularized (composite) applications.

Manually implementing IoC with a Windows Service

I am brand new to IoC and thus have been following the examples provided by Jeffery Palermo in his posts at http://jeffreypalermo.com/blog/the-onion-architecture-part-1/ and in his book hosted here https://github.com/jeffreypalermo/mvc2inaction/tree/master/manuscript/Chapter23
Most important to note is that I am not using a pre-rolled IoC container, mostly because I want to understand all the moving parts.
However, I am creating a windows service rather than an ASP.NET MVC webapp so I am little bogged down on the startup portion. Specifically, in the web.config he registers an IHttpModule implementation INSIDE the infrastructure project as the startup module and then uses a post-build event to copy the necessary dlls into the website directory to get around having a direct dependency in the web project itself.
I don't think I have this type of luxury in a true windows service, so how do I achieve something similar, should I have a small startup project which has dependencies to both the Infrastructure and Core, or is there another method to get around the compile-time restrictions of the windows service?
Thanks in advance.
Based on the tags of this question (c#) I'm assuming that you'll implement the Windows Service by deriving from ServiceBase. If so, the OnStart method will be your Composition Root - this is where you compose the application's object graph. After you've composed the object graph, composition is over and the composed object graph takes over.
In OnStop you can decommission the object graph again.
There's nothing stopping you from implementing the various components of the resolved object graph in separate assemblies. That's what I would do.
I think you missunderstood the role of an IoC framework.
To answer your question
but doesn't the reference imply dependency?
Yes it does, but on an other level. IoC is about dependencies between classes.
Instead of using new Something() in your class you provide a constructor which requires all dependent interfaces. This way the class has no control which implementation is passed to it. This is inversion of control. The IoC Container is just an aid to help managing the dependencies in a nice manner.
Say you have a ICustomerNotificationService interface with an implementation like
public class MailNotificationService : INotificationService
{
IMailerService _mailer;
ICustomerRepository _customerRepo;
IOrderRepository _orderRepo;
public MailNotificationService(IMailerService mailer,
ICustomerRepository customerRepo,
IOrderRepository oderRepo)
{
// set fields...
}
public void Notify(int customerId, int productId)
{
// load customer and order, format mail and send.
}
}
So if your application requests an instance of ICustomerNotificationServcie the container figures out which concrete implementations to take and tries to satisfy all dependencies the requested class has.
The advantage is that you can easily configure all dependencies in your bootstrapping logic and be able to change the behaviour of your application very easily.
For example when testing you start the application with an IMailerService implementation which writes the mails to a file and in production mode a real mail service is wired. This would not be possible if you newed up say a MailerService in your constructor instead of taking it as a parameter.
A good IoC container can handle much more, for you like lifetime management, singletons, scanning assemblies for Types you want to register and many more. We based our entire plugin system on Structure Map for example.
You may want to take a look at this blog article and its second part.

Categories