How to prevent constructor misuse in c# class - c#

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.

Related

Injecting a dependency that is a static variable in a class

A WinForms application uses the following "configuration class" (partial code):
public class Configuration
{
public static Project currentProject;
}
Many other classes in the application currently use this Project variable, for example:
public class Controller
{
public void processSomething()
{
Configuration.currentProject.doSomething();
}
}
For the purposes of loose coupling, I want to be able to inject a Project variable as a dependency. The problem is, the Configuration.currentProject value might change at runtime. How should this be dealt with? Can passing it by reference solve it?
I'd suggest passing in a Func<IProject> or Func<Project>. This will allow you to nicely handle changes to Configuration.currentProject (since invoking the function will always see the current value of the static) and also allow relatively easy writing of unit tests.
That being said, I'd strongly encourage you to move away from use of static and manual dependency injection. If you used a IoC container (e.g. Autofac) then Func and singleton support (without static) will likely be built in.

Autofac injecting dependencies to controller error [duplicate]

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)

Prevent dependencies being required by other projects

I am writing a project which will encapsulate multiple Calendar APIs (Google Calendar, Outlook ect) in one service. This will allow me to integrate different APIs which can be mapped to our domain model. However I am having issues with required dependencies spilling over into other projects. Here's an example:
I have created a generic class which does most of the work and conversions from the API model to our model. Here's an example:
public abstract class CalendarAPIBase<TEventType> : ICalendarAPI
{
public CalendarEvent Get(string id)
{
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException("id");
return Convert(GetEvent(id));
}
public List<CalendarEvent> GetAll()
{
List<CalendarEvent> result = new List<CalendarEvent>();
List<TEventType> es = GetAllEvents();
foreach (TEventType e in es)
result.Add(Convert(e));
return result;
}
protected abstract List<TEventType> GetAllEvents();
protected abstract CalendarEvent Convert(TEventType obj);
//More stuff below.
}
So this is a beautiful thing, anything that inherits CalendarAPIBase doesn't have to do much work other than getting the data from the API, the base class will handle the conversions.
Ok, so here's where things go wrong. I have created a GoogleCalendarAPI class, which inherits from CalendarAPIBase. It passes in the Event class, which belongs to a NuGet package Google.Apis.Calendar.v3.
public class GoogleCalendarAPI : CalendarAPIBase<Event>
The problem here is that this class is exposing the Event class, therefore anything that references this project will also need to reference Google.Apis.Calendar.v3. Ideally anyone wishing to use this service will only have to reference just the project and not have to worry about installing other NuGet packages.
How can I restructure my classes to prevent this from happening?
The most straightforward way to resolve this stuff is an Abstract factory pattern.
First, you make CalendarAPIBase<TEventType> and all its descendants internal. All the public stuff has to be concentrated within a public ICalendarAPI interface.
Next step is introducing public classes like this:
public static class GoogleCalendarAPIFactory
{
public static ICalendarAPI Instantiate( ....... )
{
.......
return new GoogleCalendarAPI( ..... );
}
}
The factory will make all the TEventType hassle hidden ftom the library user, therefore he will not need to add all the packages containing TEventType implementations.
I'm not sure if you can avoid referencing 3rd party assemblies if you use classes like Google.Apis.Calendar.v3.Event directly in your code.
However, you can use ILMerge to merge 3rd party API into your own, that way the dependencies of your assemblies will be deployed along with your assemblies.
I usually use ILMerge in the post build event.
For example:
After GoogleCalendarAPI project is built, merge GoogleCalendarAPI.dll and Google.Apis.Calendar.v3.dll and save it in "GoogleCalendarAPI_location\mergerd\GoogleCalendarAPI.dll"
Copy "GoogleCalendarAPI_location\mergerd\GoogleCalendarAPI.dll" to the location of the original GoogleCalendarAPI.dll and replace it.
Now you've got GoogleCalendarAPI.dll with Google.Apis.Calendar.v3 baked into it.
Now every assembly that references GoogleCalendarAPI.dll gets both.

What is the intention of Ninject modules?

I'm a complete newbie to ninject
I've been pulling apart someone else's code and found several instances of nInject modules - classes that derive from Ninject.Modules.Module, and have a load method that contains most of their code.
These classes are called by invoking the LoadModule method of an instance of StandardKernel and passing it an instance of the module class.
Maybe I'm missing something obvious here, but what is the benefit of this over just creating a plain old class and calling its method, or perhaps a static class with a static method?
The Ninject modules are the tools used to register the various types with the IoC container. The advantage is that these modules are then kept in their own classes. This allows you to put different tiers/services in their own modules.
// some method early in your app's life cycle
public Kernel BuildKernel()
{
var modules = new INinjectModule[]
{
new LinqToSqlDataContextModule(), // just my L2S binding
new WebModule(),
new EventRegistrationModule()
};
return new StandardKernel(modules);
}
// in LinqToSqlDataContextModule.cs
public class LinqToSqlDataContextModule : NinjectModule
{
public override void Load()
{
Bind<IRepository>().To<LinqToSqlRepository>();
}
}
Having multiple modules allows for separation of concerns, even within your IoC container.
The rest of you question sounds like it is more about IoC and DI as a whole, and not just Ninject. Yes, you could use static Configuration objects to do just about everything that an IoC container does. IoC containers become really nice when you have multiple hierarchies of dependencies.
public interface IInterfaceA {}
public interface IInterfaceB {}
public interface IInterfaceC {}
public class ClassA : IInterfaceA {}
public class ClassB : IInterfaceB
{
public ClassB(IInterfaceA a){}
}
public class ClassC : IInterfaceC
{
public ClassC(IInterfaceB b){}
}
Building ClassC is a pain at this point, with multiple depths of interfaces. It's much easier to just ask the kernel for an IInterfaceC.
var newc = ApplicationScope.Kernel.Get<IInterfaceC>();
Maybe I'm missing something obvious
here, but what is the benefit of this
over just creating a plain old class
and calling its method, or perhaps a
static class with a static method?
Yes, you can just call a bunch of Bind<X>().To<Z>() statements to setup the bindings, without a module.
The difference is that if you put these statements in a module then:
IKernel.Load(IEnumerable<Assembly>) can dynamically discover such modules through reflection and load them.
the bindings are logically grouped together under a name; you can use this name to unload them again with IKernel.Unload(string)
Maybe I'm missing something obvious here, but what is the benefit of this over just creating a plain old class and calling its method, or perhaps a static class with a static method?
For us, it is the ability to add tests at a later time very easily. Just override a few bindings with mockobjects and voila.....on legacy code without a DI that wired "everything" up, it is near impossible to start inserting test cases without some rework. With a DI in place AND as long as it was used properly where the DI wired everything up, it is very simple to do so even on legacy code that may be very ugly.
In many DI frameworks, you can use the production module for your test with a test module that overrides specific bindings with mockobjects(leaving the rest of the wiring in place). These may be system tests more than unit tests, but I tend to prefer higher level tests than the average developer as it tests the integration between classes and it is great documentation for someone who joins the project and can see the whole feature in action(instead of just parts of the feature) without having to setup a whole system).

IoC, Dll References, and Assembly Scanning

Although this question is related to StructureMap, my general question is:
When wiring up components with an IoC
container in code (as opposed
to configuring via xml) do you
generally need explicit project/build
references to all assemblies?
Why the separate assemblies? Because:
"Abstract classes residing in a
separate assembly from their concrete
implementations are a great way to
achieve such separation." -Framework
Design Guidelines p.91
Example:
Let's say I have PersonBase.dll and Bob.dll
Bob inherits from the abstract class PersonBase. They're both in the Person namespace. But in different assemblies.
I'm programming to PersonBase, not Bob.
Back in my main code, I need a person. StructureMap can scan assemblies. Great, I'll ask StructureMap for one!
Now, in my main code, I am of course referring only to PersonBase, not to Bob. I actually don't want my code to know anything about Bob. No project references, no nuthin. That's the whole point.
So I want to say:
//Reference: PersonBase.dll (only)
using Person;
...
//this is as much as we'll ever be specific about Bob:
Scan( x=> { x.Assembly("Bob.dll"); }
//Ok, I should now have something that's a PersonBase (Bob). But no ?
ObjectFactory.GetAllInstances<PersonBase>().Count == 0
No luck. What does work is being explicit that I want Bob:
//Reference: PersonBase.dll and Bob.dll
using Person;
...
Scan( x => {x.Assembly("Bob.dll"); }
//If I'm explicit, it works. But Bob's just a PersonBase, what gives?
ObjectFactory.GetAllInstances<Bob>().Count == 1 //there he is!
But now I've had to reference Bob.dll in my project which is exactly what I didn't want.
I can avoid this situation using Spring + Xml configuration. But then I'm back to Spring + Xml configuration ... !
Am I missing something with using
StructureMap, or as a general
principle, do (fluent) IoC
configurations need explict references
to all assemblies?
Possibly related question: StructureMap and scanning assemblies
I finally got this sorted out. It looks like this:
IoC Uml http://img396.imageshack.us/img396/1343/iocuml.jpg
with the assemblies
Core.exe
PersonBase.dll (referenced compile time by Core.exe)
Bob.dll (loaded up run time via StructureMap Scan)
Betty.dll (loaded up run time via StructureMap Scan)
To get it with StructureMap, I needed a custom "ITypeScanner" to support scanning for assemblies:
public class MyScanner : ITypeScanner {
public void Process(Type type, PluginGraph graph) {
if(type.BaseType == null) return;
if(type.BaseType.Equals(typeof(PersonBase))) {
graph.Configure(x =>
x.ForRequestedType<PersonBase>()
.TheDefault.Is.OfConcreteType(type));
}
}
}
So my main code looks like:
ObjectFactory.Configure(x => x.Scan (
scan =>
{
scan.AssembliesFromPath(Environment.CurrentDirectory
/*, filter=>filter.You.Could.Filter.Here*/);
//scan.WithDefaultConventions(); //doesn't do it
scan.With<MyScanner>();
}
));
ObjectFactory.GetAllInstances<PersonBase>()
.ToList()
.ForEach(p =>
{ Console.WriteLine(p.FirstName); } );
You can do xml configuration with StructureMap as well. You can even mix them if you want.
There are also StructureMap Attributes you could put in your Bob class to tell StructureMap how to load the assembly. DefaultConstructor is one I end up using from time to time.
The automatic scan option only works when you keep the naming, assembly and namespace conventions. You can manually configure structuremap with a fluent interface. Example:
ObjectFactory.Initialize(initialization =>
initialization.ForRequestedType<PersonBase>()
.TheDefault.Is.OfConcreteType<Bob>());
What we do on my current project (which uses AutoFac, not StructureMap, but I think it shouldn't make a difference):
We have the interfaces defining external services that the application uses in a core assembly, let's say App.Core (like your PersonBase).
Then we have the implementations of these interfaces in Services.Real (like Bob.dll).
In our case we also have Service.Fake, which are used for facilitating UI testing with dependencies on other enterprise services and databases, etc.
The front-end "client" application itself (in our case, ASP.NET MVC app) references App.Core.
When the app starts, we use Assembly.Load to load the appropriate "Services" implementation DLL, based on a config setting.
Each of these DLLs has an implementation of IServiceRegistry that returns a list of the services that it implements:
public enum LifestyleType { Singleton, Transient, PerRequest}
public class ServiceInfo {
public Type InterfaceType {get;set;}
public Type ImplementationType {get;set;}
// this might or might not be useful for your app,
// depending on the types of services, etc.
public LifestyleType Lifestyle {get;set;}
}
public interface IServiceRegistry {
IEnumerable<ServiceInfo> GetServices();
}
... the application finds this ServiceRegistry via reflection and enumerates through these ServiceInfo instances and registers them on the container. For us, this register-all-services lives in the Web application, but it's possible (and preferable in many cases) to have it in a separate assembly.
This way we can isolate the domain logic from the infrastructure code, and prevent "just-this-once" work-arounds where the application ends up depending on a direct reference to the infrastructure code. We also avoid having to have a reference to the container in each Services implementation.
One really important thing if you are doing this: make sure that you have tests that verify that you can create each "top-level" type (in our case, ASP.NET MVC Controllers) with each potential configuration of the IOC container.
Otherwise, it is pretty easy to forget to implement one interface and break huge sections of your application.

Categories