Autofac injecting dependencies to controller error [duplicate] - c#

I am creating one demo application to learn how to use repository pattern for performing Insert operation.I am using Nop Commerce**(http://www.nopcommerce.com) **code for repository pattern
Error:No parameterless constructor defined for this object
I have seen this link:MVC: No parameterless constructor defined for this object
This is my Structure:
My Repository interface:
public partial interface IRepository<T>
{
void Insert(T entity);
}
My Service Layer:
public partial interface IEmployeeService
{
void InsertCategory(EmployeeMaster employeeMaster);
}
My Class which will implement that interface(service):
public partial class EmployeeService : IEmployeeService
{
#region Fields
private readonly IRepository<EmployeeMaster> _employeeMasterRepository;
#endregion
#region Ctor
public EmployeeService
(
IRepository<EmployeeMaster> employeeMasterRepository
)
{
this._employeeMasterRepository = employeeMasterRepository;
}
#endregion
public virtual void InsertCategory(EmployeeMaster employeeMaster)
{
if (employeeMaster == null)
throw new ArgumentNullException("employeeMaster");
_employeeMasterRepository.Insert(employeeMaster);
}
This is my controller:
public class HomeController : Controller
{
#region Fields
private readonly IEmployeeService _employeeService;
#endregion
#region Constructors
public HomeController
(
IEmployeeService employeeService
)
{
this._employeeService = employeeService;
}
#endregion
Getting Error:No parameterless constructor defined for this object
I have studied regarding this error and all the sources are saying that use Dependency injection to solve this error.
Can anybody guide me how to use dependency injection to solve this error??

Maybe you're taking as a sample a project that is too complex for you at this moment. Nopcommerce is a big and full featured product that has a lot of elements, so it easy to get lost. Not the best sample to learn how the repository pattern works, but I certainly recommend you to check it again once you have the basic concepts clear to see them used in a real scenario.
NopCommerce uses Autofac for dependency injection, a very popular IoC container. You can look for a class called DependencyRegistrar in the project Nop.Web.Framework to see how it is used, if you're curious about it. You can get more examples on how to use dependency injection with Autofac in their repository and their getting started guide.
My recommendation is to look for an easier to follow example. For starters, any of the popular IoC containers will be OK until you have your own criteria to choose one. For instance you can follow the Autofac's guide for MVC

You're correct - you'll need to use something like Unity, Ninject or Autofac to get this running.
Essentially - the steps are roughly the same regardless of the tech used.
Using unity as an example:
1) In your MVC project, use NuGet to add "Unity Bootstrapper for MVC". (right click references, manage nuget packages, search for unity online, select "Unity Bootstrapper for MVC"
This will add a few things to your project - the most interesting is the unityConfig.cs in App_start.
2) In unityConfig.cs - find RegisterTypes method
RegisterTypes is where you tell the unity container "when you need one of X, use implementation Y" - in your case "when you need an IEmployeeService, use EmployeeService"
3) In register types - add your type mappings - for example, in your case:
container.RegisterType<IEmployeeService, EmployeeService>();
AND
4) Bit more complicated: as you have IRepository and you need this to resolve your employeeService correctly you'll also have to register a generic type against a generic implementation (it's a little odd). Looking at your types, it's going to be something like:
container.RegisterType(typeof(IRepository<>), typeof(Repository<>));
(You'll need to resolve the namespaces according to your projects).
So - what this is saying is...
Right MVC - when you need an IEmployeeService use employeeService, and
when you need an IRepository<>, use Repository<>
Now - because of the webActivator that was added during the NuGet installation (right next door to UnityConfig.cs), that should be it - the webActivator sets the DependencyResolver.Current to something that uses this unityContainer.
Beacause of this, MVC will now use this new unityContainer whenever it tries to instantiate your controllers, resolving the type mappings on the way.
The webActivator and unityConfig classes do alot of the heavy-lifting for you, just elaborate registerTypes and you should at least have a foot-hold in the solution.
HTH - good luck.
PS - DI itself is a massive subject - far too much for here, you'll bump into all sort of weird and wonderful things (supplying Ctor args for resolutions, lifetime management just for a start!) - it's fun, but not trivial, so you'll have to excuse me if this doesn't work "out of the box" (it's almost impractical to think it would) - this is merely just a vague attempt to give you a foothold in the subject!
For more info on unity - I suggest you read up here (Dev guide to using Unity on MSDN)

Related

ASP.NET Core and ViewModelFactory

Hello, I'm trying to implement a ViewModelFactory "pattern" and I was wondering what's the best way to achieve it, considering the constraints of the current IoC container.
public class UserCreateViewModelFactory
{
private readonly DbContext db;
public UserCreateViewModelFactory(DbContext db){ this.db = db;}
public void Create(CreateUserViewModel viewModel)
{
//Creates the user
}
}
I have the above class easily injected into my controllers ctor. The head ache will come when I need more ViewModelBuilders, So I want to avoid two things:
Bloat ctor with injections
Bloat container with registrations
I want to be able to inject an IViewModelFactory on my controller and then using it like this:
[HttpGet]
public IActionResult GetUsers(int id)
{
return View(viewModelFactory.Build<GetUserViewModel>(id));
}
Notice that on calling Build(T) it has to call the correct IViewModelFactory implementation.
I know that StructureMap container support binding the concrete implementations to the corresponding interface but I'm trying to come up with a solution without having to add another dependecy to the project.
I think if you have builders for building viewmodels, then factory is extra layer of abstraction which simply can be dropped off.
Because you know the type of created viewmodel at compile time you can just inject a builder you need to the controller constructor.
If your controller create a lot of viewmodels and you end up with a lot of builders you need to inject - this can be considered as a sign of violation of Single Responsibility Principle. In that case you need to separate logic of controller to different controllers.
So I want to avoid two things:
Bloat ctor with injections
Separate class with bloated constructor to another classes with more specific responsibility which takes smaller amount of dependencies.
Or wrap dependencies with one or two, three classes based on their relation
Bloat container with registrations
This cannot be a problem, because dependency containers is usually designed to register whole "object graph" of your application
After sometime researching, I finally came up with a good solution for the this problem.
The solution is basically extending the default IoC capabilities through an IServiceCollection.ConnectImplementations() extension method.
During registration I'll search my concrete classes and connect them with its respective interfaces (like other containers). Then I use a Mediator/Proxy that has IServiceCollection injected and knows which concrete class should be building the view model.
The full solution is better explained by this gist I've created.

How to prevent constructor misuse in c# class

I've been trying to implement a loosely coupled application in an asp.net MVC5 app. I have a controller:
public class HeaderController : Controller
{
private IMenuService _menuService;
public HeaderController(IMenuService menuService)
{
this._menuService = menuService;
}
//
// GET: /Header/
public ActionResult Index()
{
return View();
}
public ActionResult GetMenu()
{
MenuItem menu = this._menuService.GetMenu();
return View("Menu", menu);
}
}
And service being used in this controller is:
public class MenuService : IMenuService
{
private IMenuRespository _menuRepository;
public MenuService(IMenuRespository menuRepository)
{
this._menuRepository = menuRepository;
}
public MenuItem GetMenu()
{
return this._menuRepository.GetMenu();
}
}
And the repository being used in the service class is:
public class MenuRepository : IMenuRespository
{
public MenuItem GetMenu()
{
//return the menu items
}
}
The interfaces used for the service and repository are as such:
public interface IMenuService
{
MenuItem GetMenu();
}
public interface IMenuRespository
{
MenuItem GetMenu();
}
The constructor for HeaderController takes in the MenuService using Constructor Injection, and I have ninject as the DI container handling this.
It all works great - except, in my controller, I can still do this:
MenuItem menu = new MenuService(new MenuRepository());
...which breaks the architecture. How can I prevent the 'new' being used in this way?
One way to do it would be to move your interfaces and implementations into separate Visual Studio projects / assemblies and only reference the implementation project in the project(s) that actually needs it - everything else can reference the interface project for your IMenuService - at that point the code can consume the interface, but not actually new up any implementations itself.
You can then reference the implementation project wherever you DI in your dependencies.
WebApp Solution:
WebApp Proj (Controllers etc.) --> Service Interface Proj
Service Impl Project --> Service Interface Proj
Even so this is a good approach, it's not fool proof by all means - the other component is education and code review to come up with best practices that work for your team such as testability and dependency injection.
I assume part of the issues with manually instantiating the object may come with working with a large team, whereby some members are using the constructor injection technique the wrong way. If that is the case, I found pretty much by educating them on the framework resolved most of the issues. Occasionally, you would find someone doing it the wrong way, but not often. Another alternative could be to add an [EditorBrowsable(EditorBrowsableState.Never)] attribute on the controller constructor. The constructor will disappear from intellisense; well, it will appear to be gone. It can still be used, however.
You could break out the implementations into another DLL not directly references (implicitly referenced) by the MVC project, and thus since there isn't a direct reference, you can't use those types directly. With the interfaces in one project, which each project references, and the project with the implementations indirectly referenced, only the interfaces would thus be included. I'd recommend including a direct reference in the unit test project, if you are doing unit tests, to enhance test coverage.
Couple of potential options (which I've never tried, but might have some legs):
you could maybe write an FXCop rule which errors if the constructor is used in the code.
you could mark the constructor as obsolete, and have the build server fail if you use obsolete methods in the code.
If the DI container uses it through reflection this should all be ok (although in the FXCop case you could probably not throw if it was in a method in the NInject namespace)
As general design principle, interfaces (Contracts) should be in one assembly and the implementation should in another assembly. The Contracts assembly should be reference in MVC project and implemented assembly should be copied in "bin" folder. Than use "Dynamic Module Loading" to load types. In this way you will avoid the above mentioned problem and this is more extensive solution. Because you can replace implementation without building UI and Contact Assemblies.

Is this the Service Locator Anti Pattern and a poor solution?

I have implemented a solution that has some core reusable classes that are easily registered and resolved using StructureMap. I then have an abstract factory to load additional families of products at runtime.
If I have a StructureMap registries like this one:
public ProductAClaimsRegistry()
{
var name = InstanceKeys.ProductA;
this.For<IClaimsDataAccess>().LifecycleIs(new UniquePerRequestLifecycle()).Use<ProductAClaimsDataAccess>().Named(name)
.Ctor<Func<DbConnection>>().Is(() => new SqlConnection(ConfigReader.ClaimsTrackingConnectionString));
this.For<IClaimPreparer>().LifecycleIs(new UniquePerRequestLifecycle()).Use<ProductAClaimPreparer>().Named(name);
this.For<IHistoricalClaimsReader>().LifecycleIs(new UniquePerRequestLifecycle()).Use<ProductAHistoricalClaimReader>().Named(name);
this.For<IProviderClaimReader>().LifecycleIs(new UniquePerRequestLifecycle()).Use<ProductAProviderClaimReader>().Named(name);
}
There may be a version for ProductB, ProductC and so on.
My abstract factory then loads the correct named instance like this:
public abstract class AbstractClaimsFactory
{
private IClaimsReader claimsReader;
private IClaimPreparer claimPreparer;
protected string InstanceKey { get; set; }
public virtual IClaimsReader CreateClaimReader()
{
return this.claimsReader;
}
public virtual IClaimPreparer CreateClaimPreparer()
{
return this.claimPreparer;
}
public void SetInstances()
{
this.CreateInstances();
var historicalReader = ObjectFactory.Container.GetInstance<IHistoricalClaimsReader>(this.InstanceKey);
var providerReader = ObjectFactory.Container.GetInstance<IProviderClaimReader>(this.InstanceKey);
this.claimsReader = new ClaimsReader(historicalReader, providerReader);
this.claimPreparer = ObjectFactory.Container.GetInstance<IClaimPreparer>(this.InstanceKey);
}
protected abstract void CreateInstances();
}
At runtime there is a processor class that has a concrete factory injected like this:
public void Process(AbstractClaimsFactory claimsFactory)
{
// core algorithm implemented
}
A concrete factory then exists for each product:
public class ProductAClaimsFactory : AbstractClaimsFactory
{
public ProductAClaimsFactory()
{
SetInstances();
}
protected override void CreateInstances()
{
InstanceKey = InstanceKeys.ProductA;
}
}
EDIT
The classes loaded in the factory are used by other classes that are Product agnostic - but they need to inject ProductA or ProductB behaviour.
public ClaimsReader(IHistoricalClaimsReader historicalClaimsReader, IProviderClaimReader providerClaimsReader)
{
this.historicalClaimsReader = historicalClaimsReader;
this.providerClaimsReader = providerClaimsReader;
}
I'm not exactly sure if this a text book abstract factory pattern and I'm new to StructureMap and more advance DI in general.
With this solution I think I have enforced a core algorithm and reused code where appropriate.
I also think that it is extensible as ProductN can easily be added without changing existing code.
The solution also has very good code coverage and the tests are very simple.
So, bottom line is: I am fairly happy with this solution but a colleague has questioned it, specificly around using ObjectFactory.Container.GetInstance<IClaimPreparer>(this.InstanceKey); to load named instances and he said it looks like the Service Locator anti pattern.
Is he correct?
If so, can anyone point out the downsides of this solution and how I might go about improving it?
This is service location. It's a problem as you have introduced a dependency on your service locator, ObjectFactory, rather than the interface, IClaimPreparer, your AbstractClaimsFactory class actually needs. This is going to make testing harder as you'll struggle to fake an implementation of IClaimPreparer. It also clouds the intention of your class as the class's dependencies are 'opaque'.
You need to look into the use of a Composition Root to resolve the anti-pattern. Have a look at Mark Seemann's work to find out more.
He's partially correct. Given a good DI container it is possible to register all your components and resolve the root object in your object tree... the DI container handles creating all the dependency for the root object (recursively) and creates the whole object tree for you. Then you can throw the DI container away. The nice thing about doing it that way is all references to DI container are confined to the entry-point of your app.
However, you are at least one step ahead of the curve since you didn't resolve dependencies in the constructor (or somewhere else) of the object using them, but instead resolved those in the factory and passed them in to the objects that need them via constructor-injection ;) (That's something I see often in code I work on and that is definitely an anti-pattern.
Here's a bit more about service locators and how they can be an anti-pattern:
http://martinfowler.com/articles/injection.html
http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/
Here's a bit more about the configure-resolve-release type pattern I hinted at:
http://blog.ploeh.dk/2010/08/30/Dontcallthecontainer;itllcallyou/
http://kozmic.net/2010/06/20/how-i-use-inversion-of-control-containers/

Is it a good design practice to have an interface for each service class in DDD?

I just have started to design with DDD (I have no experience neither a teacher)
I have some domain service classes that have to reference each other in some point. So I decided to inject the references through constructor.
And when I created a view that has a lot of data to display in the controller I had to create a bunch of service (some of which referencing each other)
At this point one of my controller's first lines looked like this:
EmployeeRepository employRepository = new EmployeeRepository();
ShiftModelRepository shiftModelRepository = new ShiftModelRepository();
ShiftModelService shiftModelService = new ShiftModelService(shiftModelRepository);
EmployeeService employeeService = new EmployeeService(employRepository, shiftModelService);
OvertimeRepository overtimeRepository = new OvertimeRepository();
OvertimeService overtimeService = new OvertimeService(overtimeRepository, employeeService);
But I started to create interfaces for the services and using a IoC controller (named StructureMap)
And now the same controller's first lines looked like this:
IShiftModelService shiftModelService = ObjectFactory.GetInstance<IShiftModelService>();
IOvertimeService overtimeService = ObjectFactory.GetInstance<IOvertimeService>();
IEmployeeService employeeService = ObjectFactory.GetInstance<IEmployeeService>();
I think that it's far more good to use, but I to know if it is a good practice in DDD or not.
Using interfaces is almost always preferable and good practice - so what you have in the second example is better.
But as StuartLC mentions, your really want to look at injecting these dependencies as constructor arguments.
ObjectFactory.GetInstance is really a kind of service locator which is generally not the best pattern to use as the object doesn't declare what dependencies it has. It is generally better to expose the dependencies as constructor arguments and have them injected in.
Yes, it is OK to use an interface per implementation when you use DI (dependency injection) frameworks.
You should avoid ObjectFactory.GetInstance<IShiftModelService>() and let your framework resolve dependencies automatically using YourImplementationOfControllerFactory.
I haven't used Structure Map in my projects but I've been using Castle Windsor, another one dependency injection framework. Also you can have a look at Ninject.
Anyway, there are steps that are similar for many frameworks:
Write a custom implementation of controller factory - a class that
inherits DefaultControllerFactory.
Register types that container should resolve.
Bootstrap container in Global.asax.cs.
Set up an instance of your controller factory in Global.asax.cs.
Global.asax.cs:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
/* code that bootstraps your container */
//Set the controller builder to use our custom controller factory
var controllerFactory = new YourControllerFactory();
ControllerBuilder.Current.SetControllerFactory(controllerFactory);
}
}
There are several useful links:
Castle Windsor for StructureMap users
Windsor tutorial - ASP.NET MVC 3 application
ASP.NET MVC Tip: Dependency Injection with StructureMap
An another my SO answer about Castle Windsor set up steps

Benefit of IoC over my Factory Singleton

There seems to be a stigma on SO regarding use of Singletons. I've never personally bought into it but for the sake of open mindedness I'm attempting to give IoC concepts a try as an alternative because I'm frankly bored with my everyday work and would like to try something different. Forgive me if my interpretation of IoC concepts are incorrect or misguided.
Here's the situation: I'm building a simple HttpListener based web server in a windows service that utilizes a plug-in model to determine how a request should be handled based on the URL requested (just like everyone else that asks about HttpListener). My approach to discovering the plug-ins is to query a configured directory for assemblies decorated with a HttpModuleAssemblyAttribute. These assemblies can contain 0 or more IHttpModule children who in addition are decorated with a HttpModuleAttribute used to specify the module's name, version, human readable description and various other information. Something like:
[HttpModule(/*Some property values that matter */)]
public class SimpleHttpModule : IHttpModule
{
public void Execute(HttpListenerContext context)
{
/* Do Something Special */
}
}
When an HttpModule is discovered I would typically add it to a Dictionary<string, Type> object who's sole purpose is to keep track of which modules we know about. This dictionary would typically live in my variety of a Singleton which takes on the persona of an ACE style Singleton (a legacy from my C++ days where I learned about Singletons).
Now what I am trying to implement is something similar using (my understanding of) general IoC concepts. Basically what I have is an AppService collection where IAppService is defined as:
public interface IAppService : IDisposable
{
void Initialize();
}
And my plug-in AppService would look something like:
[AppService("Plugins")]
internal class PluginAppService : IAppService, IDictionary<string, Type>
{
/* Common IDictionary Implementation consisting of something like: */
internal Type Item(string modName)
{
Type modType;
if (!this.TryGetValue(modName, out modType)
return null;
return modType;
}
internal void Initialize()
{
// Find internal and external plug-ins and add them to myself
}
// IDisposable clean up method that attempts to dispose all known plug-ins
}
Then during service OnStart I instantiate an instance of AppServices which is locally known but passed to the constructor of all instantiated plug-ins:
public class AppServices : IDisposable, IDictionary<string, IAppService>
{
/* Simple implementation of IDictionary */
public void Initialization()
{
// Find internal IAppService implementations, instantiate them (passing this as a constructor parameter), initialize them and add them to this.
// Somewhere in there would be something like
Add(appSvcName, appSvc);
}
}
Our once single method implementation becomes an abstract implementation + a constructor on the child:
[HttpModule(/*Some property values that matter */)]
public abstract class HttpModule : IHttpModule
{
protected AppServices appServices = null;
public HttpModule(AppServices services)
{
appServices = services;
}
public abstract void Execute(HttpListenerContext context);
}
[HttpModule(/*Some property values that matter */)]
public class SimpleHttpModule : HttpModule
{
public SimpleHttpModule(AppServices services) : base(services) { }
public override void Execute(HttpListenerContext context)
{
/* Do Something Special */
}
}
And any access to commonly used application services becomes:
var plugType = appServices["Plugins"][plugName];
rather than:
var plugType = PluginManager.Instance[plugName];
Am I missing some basic IoC concept here that would simplify this all or is there really a benefit to all of this additional code? In my world, Singletons are simple creatures that allow code throughout a program to access needed (relatively static) information (in this case types).
To pose the questions more explicitly:
Is this a valid implementation of a Factory Singleton translated to IoC/DI concepts?
If it is, where is the payback/benefit for the additional code required and imposition of a seemingly more clunky API?
IoC is a generic term. Dependency Injection is the more preferred term these days.
Dependency Injection really shines in several circumstances. First, it defines a more testable architecture than solutions that have hard-coded instantiations of dependencies. Singletons are difficult to unit test because they are static, and static data cannot be "unloaded".
Second, Dependency Injection not only instantiates the type you want, but all dependant types. Thus, if class A needs class B, and class B needs class C and D, then a good DI framework will automatically create all dependencies, and control their lifetimes (for instance, making them live for the lifetime of a single web request).
DI Containers can be though of as generic factories that can instantiate any kind of object (so long as it's properly configured and meets the requirments of the DI framework). So you don't have to write a custom factory.
Like with any generic solution, it's designed to give 90% of the use cases what they need. Sure, you could create a hand crafted custom linked list data structure every time you need a collection, but 90=% of the time a generic one will work just fine. The same is true of DI and Custom Factories.
IoC becomes more interesting when you get round to writing unit tests. Sorry to answer a question with more questions, but... What would the unit tests look like for both of your implementations? Would you be able to unit test classes that used the PluginManager without looking up assemblies from disk?
EDIT
Just because you can achieve the same functionality with singletons doesn't mean it's as easy to maintain. By using IoC (at least this style with constructors) you're explicitly stating the dependencies an object has. By using singletons that information is hidden within the class. It also makes it harder to replace those dependencies with alternate implementations.
So, with a singleton PluginManager it would difficult to test your HTTP server with mock plugins, rather it looking them up from some location on disk. With the IoC version, you could pass around an alternate version of the IAppService that just looks the plugins up from a pre-populated Dictionary.
While I'm still not really convinced that IoC/DI is better in this situation, I definitely have seen benefit as the project's scope crept. For things like logging and configurability it most certainly is the right approach.
I look forward to experimenting with it more in future projects.

Categories