AutoFac / Unity Container - Dependency Injection with multiple implementations - asp.net

I am going to work with Dependency Injection for a ASP.NET Web API project.
I understand how constructor Dependency Injection works, but i can't resolve how to make the injector choose between two implementations of the same interface. Lets say for an example that we have an interface like this:
public interface ISender
{
void Send();
void AddReceipment(User user);
}
Then lets say i have 2 implementations of this SmsSender and MailSender using the same ISender interface.
Now i have two API controllers lets call them "MailController" and "SmsController".
Now i want the dependency injector to inject ISender into the MailController with the implementation of the class MailSender and in the SmsController i want to inject ISender too, but with the implementation of the class SmsSender.
Is that possible using AutoFac or Unity container?
If it is, then how would i aproach that?

According to the Autofac docs, you have 4 options to achieve this:
Redesign your interfaces
Change the registrations
Use keyed services
Use metadata

Related

Autofac + MVC5: Resolving a Service's Dependencies

I've gotten the basics done with resolving controller dependencies with Autofac + MVC5. However, I'm wondering how to inject dependencies into services.
Given a sample definition as such, how can I create/get an instantiated copy of the class with Autofac resolving the necessary dependencies?
Bar : IBar
{
Public Bar(IFoo foo, IPanda panda)
{}
}
Ultimately it just comes down to registering the type in the Container. Such as:
var builder = new ContainerBuilder();
builder.RegisterType<Bar>().As<IBar>();
var container = builder.Build();
I'm assuming you have similar code using the Builder somewhere during your initialization.
There are several different ways to register and configure dependencies, lifetimes, interceptors etc, more info here:
http://docs.autofac.org/en/latest/register/registration.html
Once everything is registered, whenever Autofac tries to instantiate your controller, it'll inspect your controller's constructor, and when it finds an IBar as dependency, it'll look for it's container registration and instantiate accordingly.
The same applies when it tries to instantiate IBar, it'll notice IFoo and IPanda and repeat the same process.
The main difference is that Autofac supports automatic registration of your controllers, just to spare you the hassle of registering each one manually.
So in the end, it'll all be chained in that manner, dependencies created as needed.
I tend to avoid using ServiceLocator style of instantiation by requesting a dependency directly, and just let Autofac provide the dependencies during construction.

EF6 (code first), MVC, Unity, and a service layer without a repository

My application is using SQL Server 2012, EF6, MVC and Web API.
It's also using a repository and assorted files such as:
DatabaseFactory.cs
Disposable.cs
IDatabaseFactory.cs
IRepository.cs
IUnitOfWork.cs
RepositoryBase.cs
UnitOfWork.cs
We already use a service layer between our controllers and the repository
for some complicated business logic. We have no plans EVER to change to a different database and it has been pointed
out to me that the recent thinking is that EF6 is a repository so why build
another repository on top of it and why have all of the files I have above.
I am starting to think this is a sensible approach.
Does anyone know of any examples out there that implement EF6 without a
repository, with a service layer. My search on the web has revealed many
complex code examples that seem over complicated for no reason at all.
My problem is also when using a Service Layer then where do I put:
context = new EFDbContext()
In the controller, the service layer or both ? I read that I can do this with dependancy injection. I already use Unity as an IOC but I don't know how I can do this.
Entity Framework IS already a Unit of Work pattern implementation as well as a generic repository implementation (DbContext is the UoW and DbSet is the Generic Repository). And I agree that it's way overkill in most apps to engineer another UoW or Generic Repository on top of them (besides, GenericRepsitory is considered to be an anti-pattern by some).
A Service layer can act as a concrete repository, which has a lot of benefits of encapsulating data logic that is specific to your business needs. If using this, then there is little need to build a repository on top of it (unless you want to be able to change your backend service technology, say from WCF to WebApi or whatever..)
I would put all your data access in your service layer. Don't do data access in your controller. That's leaking your data layer into your UI layer, and that's just poor design. It violates many of the core SOLID concepts.
But you do NOT need an additional UnitOfWork, or other layers beyond that in most cases, unless your apps are very complex and intended to work in multiple environments...
Setting up Unity for ASP.NET MVC and WebAPI is quite easy if you install and add the Unity.Mvc* and Unity.WebAPI* Nuget packages to your project. (The * is a version number, like 3 or 4 or 5. Look for the appropriate versions for your project. Here are for example the links to the Unity.Mvc 5 package and to the Untity.WebAPI 5 package.)
The usage of these packages is explained in this blog post.
The building blocks are roughly like so:
You build a unity container and register all your dependencies there, especially the EF context:
private static IUnityContainer BuildContainer()
{
var container = new UnityContainer();
container.RegisterType<MyContext>(new HierarchicalLifetimeManager());
container.RegisterType<IOrderService, OrderService>();
container.RegisterType<ICustomerService, CustomerService>();
container.RegisterType<IEmailMessenger, EmailMessenger>();
// etc., etc.
return container;
}
MyContext is your derived DbContext class. Registering the context with the HierarchicalLifetimeManager is very important because it will ensure that a new context per web request will be instantiated and disposed by the container at the end of each request.
If you don't have interfaces for your services but just concrete classes you can remove the lines above that register the interfaces. If a service needs to be injected into a controller Unity will just create an instance of your concrete service class.
Once you have built the container you can register it as dependency resolver for MVC and WebAPI in Application_Start in global.asax:
protected void Application_Start()
{
var container = ...BuildContainer();
// MVC
DependencyResolver.SetResolver(
new Unity.MvcX.UnityDependencyResolver(container));
// WebAPI
GlobalConfiguration.Configuration.DependencyResolver =
new Unity.WebApiX.UnityDependencyResolver(container);
}
Once the DependencyResolvers are set the framework is able to instantiate controllers that take parameters in their constructor if the parameters can be resolved with the registered types. For example, you can create a CustomerController now that gets a CustomerService and an EmailMessenger injected:
public class CustomerController : Controller
{
private readonly ICustomerService _customerService;
private readonly IEmailMessenger _emailMessenger;
public CustomerController(
ICustomerService customerService,
IEmailMessenger emailMessenger)
{
_customerService = customerService;
_emailMessenger = emailMessenger;
}
// now you can interact with _customerService and _emailMessenger
// in your controller actions
}
The same applies to derived ApiControllers for WebAPI.
The services can take a dependency on the context instance to interact with Entity Framework, like so:
public class CustomerService // : ICustomerService
{
private readonly MyContext _myContext;
public CustomerService(MyContext myContext)
{
_myContext = myContext;
}
// now you can interact with _myContext in your service methods
}
When the MVC/WebAPI framework instantiates a controller it will inject the registered service instances and resolve their own dependencies as well, i.e. inject the registered context into the service constructor. All services you will inject into the controllers will receive the same context instance during a single request.
With this setup you usually don't need a context = new MyContext() nor a context.Dispose() as the IOC container will manage the context lifetime.
If you aren't using a repository then I assume you would have some place to write your logic/processing that your service operation would use. I would create a new instance of the Context in that logic/process class method and use its methods directly. Finally, dispose it off right after its use probably under a "using".
The processing method would eventually transform the returned/processed data into a data/message contract which the service returns to the controller.
Keep the data logic completely separate from Controller. Also keep the view model separate from data contract.
If you move ahead with this architecture, you are going to be tightly coupling the Entity Framework with either your service or your controller. The repository abstraction gives you a couple things:
1) You are able to easily swap out data access technologies in the future
2) You are able to mock out your data store, allowing you to easily unit test your data access code
You are wondering where to put your EF context. One of the benefits of using the Entity Framework is that all operations on it are enrolled into a transaction. You need to ensure that any data access code uses the same context to enjoy this benefit.
The design pattern that solves that problem is the Unit of Work pattern, which by the looks of things, you are already using. I strongly recommend continuing to use it. Otherwise, you will need to initialize your context in your controller, pass it to your service, which will need to pass it to any other service it interacts with.
Looking at the objects you have listed, it appears to be a considerate attempt to build this app with enterprise architectural best practices. While abstractions do introduce complexity, there is no doubting the benefit they provide.

Which Pattern to choose ? Asp.net Mvc 4

I'm really confused, I learned with the book "Apress pro Asp.net Mvc 4", that the best pattern for Mvc 4, is the Dependency Injection, ( to put the Model data of the database etc... in another project (Domain) and then create interfaces and implementation to those interfaces, and then connect it to the controller with Ninja..
And all the connect to the db is only from the data-layer solution, the only model in the web solution in viewModel
The Controller
public class ProductController : Controller
{
private IProductRepository repository;
public ProductController(IProductRepository productRepository)
{
this.repository = productRepository;
}
....
}
and Ninject
ninjectKernel.Bind<IProductRepository>().To<EFProductRepository>();
and on the other hand, In my last job(webmaster) , the company used another pattern for the mvc Projects (I'm using this pattern right now).
the projects is made with only One Solution and using Static Classes to handle the data layer
I don't like the Dependency Injection, this is too complicated, and by 'f12' you see only the interface instead of the Concrete class
Some questions:
which patter is better for performance (fast website)?
is't good to use " public Db db = new Db();" in the controller, instead of use it only in the domain layer (solution)??
What is the advantages of using Dependency Injection? is't bad to use my pattern?
What is the advantages of split the project into 2 solutions for the Data Layer?
example:
public class LanguageController : AdminController
{
public Db db = new Db();
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
//
// GET: /Admin/Language/
public ActionResult Index()
{
return View(db.Languages.ToList());
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(short id)
{
Language language = db.Languages.Find(id);
db.Languages.Remove(language);
db.SaveChanges();
return RedirectToAction("Index");
}
...
}
which patter is better for performance (fast website)?
Impossible to answer. You could have non-performant code in either of these approaches. Don't try to prematurely optimize for performance, optimize for clean and supportable code and address performance bottlenecks that are actually observed in real scenarios.
is't good to use " public Db db = new Db();" in the controller, instead of use it only in the domain layer (solution)
It's a question of separating concerns and isolating dependencies. If your controller internally instantiates a connection to a database then that controller can only ever be used in the context of that database. This will make unit testing the controller very difficult. It also means that replacing the database means modifying the controller, which shouldn't need to be modified in that case.
Dependency injection frameworks are simply a way of addressing the Dependency Inversion Principle. The idea is that if Object A (the controller) needs an instance of Object B (the database object) then it should require that the instance be supplied to it, rather than internally instantiate it. The immediate benefit here is that Object B can just be an interface or abstract class which could have many different implementations. Object A shouldn't care which implementation is given to it, as long as it satisfies the same observable behavior.
By inverting the dependency (whether or not you use a dependency injection framework), you remove the dependency on the database from the controller. The controller just handles client-initiated requests. Something else handles the database dependency. This makes these two separate objects more portable and re-usable.
What is the advantages of using Dependency Injection? is't bad to use my pattern?
See above. Dependency injection is a way to achieve inversion of dependencies, which is the core goal in this case. Note that there are a few different ways to achieve this. Some frameworks prefer constructor injection, some support property/setter injection, etc. Personally I tend to go with the service locator pattern, which has the added benefit of being able to abstract the dependency of the dependency injector itself.
It's only "bad" to use your approach if you run into any problems when using it. There are good patterns to address various concerns, but if your project doesn't legitimately have those concerns then using those patterns would be over-engineering and would actually hurt the supportability of the code. So, as with anything, "it depends."
What is the advantages of split the project into 2 solutions for the Data Layer?
Two solutions? Or two projects in the same solution? (Resulting in two assemblies.) The advantage is that you can re-use one without having a dependency on the other. For example, in some of the code you posted there is an allusion to the repository pattern. If you have an assembly which serves only the purpose of implementing repositories to the back-end data then any application can use those repositories. If instead it's all implemented in the MVC application directly then no other application can use it, it's tightly coupled to the MVC application.
If you will never need to re-use that functionality, then this isn't the end of the world. If you would like to re-use that functionality, separating it into a portable assembly which internally isolates its dependencies would allow for that.

Is Repository Singleton or Static or None of these?

I have a ASP.NET web site which uses domain driven design and uses repository for its database operations.
I want to know that what is pros and cons of singleton repository and static repository and simple repository class which will new on every access?
further more if anyone can compare and guide me to use which one of them I will be appreciate.
Static and singleton aren't good solution for Repository pattern. What if your application will use 2 or more repositories in the future?
IMO the best solution is to use a Dependency Injection container and inject your IRepository interface in the classes that need it.
I suggest you to read a good book about domain driven design and a good book about dependency injection (like Mark Seeman's Dependency Injection in .NET).
With singletons and static classes your application won't be scalable
You have two singleton repositories:
class Repository<TEntity> {
static Repository<TEntity> Instance { get { ... /*using sql server*/ } }
}
class Repository2<TEntity> {
static Repository2<TEntity> Instance { get { ... /*using WCF or XML or any else */ } }
}
The services using them must have a static reference to one of them or both:
class OrderService {
public void Save(Order order) { Repository<Order>.Instance.Insert(order); }
}
How can you save your order using Repository2, if the repository is statically referenced?
A better solution is using DI:
interface IRepository<TEntity> { ... }
class SqlRepository<TEntity> : IRepository<TEntity> { ....}
class OrderService {
private readonly IRepository<TEntity> _repo;
public OrderService(IRepository<TEntity> repo) { _repo = repo; }
public void Save(Order order) { repo.Insert(order); }
}
Don't use static or singleton repositories because of:
It affects testablility, you can not mock it when unit testing.
It affects extensibility, you can not make more than one concrete implementation and you can not replace behavior without re-compiling.
It affects scalability in terms of lifecycle management, insetead depend on dependency injection framework to inject the dependency and manage lifecycle.
It affects maintainability, it forces dependency upon concrete implementation instead of abstraction.
Bottom line: DONT use static or singleton repositories
instead create repository interfaces in your domain model project, and implement these interfaces in a concrete data access project, and use dependency injection framework.
Two SOLID reasons to not have singleton repository:
Consumers of repository will be coupled to repository implementation. This will negatively affect extensibility and testabiliy. This is a DIP violation. Depend on abstractions, not on concretions.
Repository implementation will have to violate SRP because it will most likely end up managing ORM session, database connection and potentially transactions. It would also have to make thread safe guarantees because it potentially can be used from multiple threads. Instead, database connection (ORM Session) should be injected into repository implementation so that consuming code can arrange multiple repository calls into transaction.
Possible solution to both problems is Constructor Injection.
I personally respectfully disagree with previous answers.
I have developed multiple websites (one with 7 millions page views per month) and never had a single problem with my static repositories.
My static repository implementation is pretty simple and only contains objects providers as properties. A single repository can contain as many providers as you need.
Then, the providers are responsible to manage database connection and transactions. Using TransactionScope, the consumer could manage the transactions or let it to the providers.
Every providers are developed using the singleton pattern.
This way, I can get my objects by simply calling this :
var myObj = MyRepository.MyProvider.GetMyObject(id);
At any time, there is only one repository and one provider of each type in every web pool of my application. Depending on how many users you have at the same time on your site, you could set more than one web pool (but most of the time one is just enough).
I don't see where my repository/providers consumers are coupled with my repository. In fact, the implementations of my providers are totally abstracted from them. Of course, all providers returned by my repository are interfaces and I could easily change the implementation of them at any time and push my new dll on the web server. If I want to create a completely new provider with the same interface, I only have to change it in ONE place: my repository.
This way, no need to add dependency injection or having to create your own ControllerFactory (for MVC procjects).
And you still have the advantage of clean code in your controllers. You will also save a lot of repository creation and destruction every time a page is requested (which normally use reflection in your ControllerFactory).
If you are looking for a scalable solution (if you really need it which most of the time is not really a problem), my way of developing repositories should never be a problem compared to dependency injection.

Practices to register types with IoC container?

I have a solution with several projects (MyApp.Data, MyApp.BLL, MyApp.Web). I register types in Global.asax file in MyApp.Web (main web application):
builder.RegisterType<SomeService1>().As<ISomeService1>().InstancePerHttpRequest();
builder.RegisterType<SomeService2>().As<ISomeService2>().InstancePerHttpRequest();
//...etc
And I wonder whether it's a bad practice to register types and their scope using attributes in the other assemblies (for example, in MyApp.BLL). See below:
[Dependency(typeof(ISomeService1), ComponentLifeStyle.Transient)]
public class SomeService1 : ISomeService1
{
//methods and properties go here
}
Using local attributes or other ways to indicate wiring for a DI Container tightly couples the service to the DI Container, so I don't think that's a good idea.
Additionally, it may constrain your future options. If, for example, you specify the lifestyle scope, you can't reuse the service with a different scope.
In general, you should compose the application in a Composition Root (global.asax), which gives you a single location with a clearly defined responsibility where all classes are composed.
That would be much more manageable and maintainable that spreading the configuration data all over your classes.
As your question implies, it makes some sense to delegate responsibility for registration to the assembly that knows what needs to be registered. For example, if you
use the SolrNet library, it provides a method that performs component registration, to encapsulate the knowledge of what needs to be registered and to spare the library's consumer from having to learn all about the library before getting started.
However, there is a potential issue with this approach. Would your registration requirements change if you used the dependent assemblies in other applications? For example, would it make sense to register something as ComponentLifeStyle.HttpRequestScoped and then use it in a non-Web application? By delegating registration to the dependency, you are coupling the dependency to its consumer's registration requirements (and to its choice of IoC container).
Autofac (I can't speak for other IoC containers) provides a way round this. It enables you to override registrations so that the most recently registered component is used when a service is resolved. This means that you can call a library's registration method and then register your own services to override the defaults.
There is another problem with your proposed attribute-based registration - it doesn't enable you to specify a lambda expression as a component creator. How would you implement a registration like this with attributes?
builder.Register(c => new A(c.Resolve<B>()));
It might be preferable to define an IRegistrar interface, and then use reflection to search all loaded assemblies for implementations and invoke them. Perhaps something like this:
public interface IRegistrar
{
void RegisterComponents();
}

Resources