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.
Related
If I have a Layered-Architecture like:
Business-Layer -> Data Access Layer, how can I implement the Dependency-Inversion-Principal properly?
As the principal states the interface used by the lower level (DAL) should be defined by the higher level. But if I define the interface within the business layer DLL I'll get a circular dependency. Is it a good idea to move the interface into a seperate DLL that is used by both?
In my opinion - yes. Then projects in a solution will be like (but it's only an example, I don't know your specific situation):
DependencyInjectionProject.InjectInterfaces (references to all projects) - this project include logic to resolve interface dependencies
Domain.YourBusinessLogic (reference to interfaces)
Infrastructure.Interfaces
Infrastructure.Implementations (reference to interfaces)
Finally, in your end/client application you can reference to DependencyInjectionProject.InjectInterfaces which resolve dependencies within business logic.
In general, there's no downside keeping your abstractions separate. They can be implemented/extended multiple ways in multiple different projects. You will only be referencing the abstractions projects where the dependencies is needed. Without necessarily knowing about implementations.
This approach has way more upsides, than a few minor downsides like increase of projects number.
#ElConrado's not wrong, but it is a bit open to opinion. Yes, you can use separate assemblies but you don't have to; DI is not just a assembly / package level thing - but granted that's where a lot of value is since it's how you can swap parts of the system by re-deploying isolated DLL's without having to re-deploy (or compile) the whole thing.
Typically I have a Common assembly / namespace, and have my DTO's and Interfaces in there, because most of the time that works well for the size and complexity of the app I am dealing with. You could put the abstraction interfaces in a separate assembly, but I don't see what practical value that would give you.
In terms how you could do it in C#:
Assembly: MyApp.Common, Namespace: MyApp.Common.Utilities
// Utility that instantiates concrete providers
// (classes that implement the abstractions / interfaces)
// like IContentDataProvider.
public class ProviderLoader
{
public static object CreateInstance(string fullTypeNameConfigKey)
{
...
}
public static object CreateInstance(string fullTypeName)
{
...
}
}
Assembly: MyApp.Common, Namespace: MyApp.Common.Interfaces.IDataProvider
// Defines abstract data access methods
public interface IContentDataProvider
{
ContentInfo Content_SELECT_ByContentID(int contentId);
}
Assembly: MyApp.Common, Namespace: MyApp.Common.Info
// Dumb DTO's / POCO's, used by the interfaces / abstractions
// as a way of exchanging data between layers, whilst still
// maintaining a clean separation.
public class ContentInfo
{
...
}
Assembly: MyApp.SQLDataProvider, Namespace: MyApp.SQLDataProvider
References MyApp.Common
// Concrete data provider
public class ContentDataProvider : IContentDataProvider
{
public ContentInfo Content_SELECT_ByContentID(int contentId)
{
...
}
}
And now the fun part, bringing it all together:
Assembly: MyApp.Business, Namespace: MyApp.Business
References MyApp.Common
// Concrete data provider
public class ContentPublisher
{
// Not strictly necessary, but Lazy-Load is one
// way to instantiate the provider where you need it.
private static MyApp.Common.Interfaces.IDataProvider.IContentDataProvider _iContentDataProvider;
private static MyApp.Common.Interfaces.IDataProvider.IContentDataProvider IContentDataProvider
{
get
{
if (_iContentDataProvider== null)
{
// Here the type of concrete provider would
// be loaded based on a value set in a config file
// so the parameter here would be a config-key.
// But you could use other approaches.
_iContentDataProvider= MyApp.Common.Utilities.ProviderLoader.CreateInstance(...) as MyApp.Common.Interfaces.IDataProvider.IContentDataProvider;
}
return _iContentDataProvider;
}
}
// Use the IContentDataProvider to access the concrete implementation:
public static ContentItem GetContentItemById(int contentId)
{
ContentInfo contentInfo = IContentDataProvider.Content_SELECT_ByContentID(contentId);
...
// Take the lowly ContentInfo DTO and use it,
// sprinkled with some other Business Layer magic,
// to return ContentItem.
}
}
Whilst it might seem a little overkill, there's no reason why you couldn't take the same approach (use of interfaces, provider loader, etc) and put it all in one assembly, and let your app's users leverage it - e.g. to choose which algorithm gets used for some purpose. They could do that via config setting, or even just by changing the app's state in-memory though the UI.
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.
For all DI examples I have seen, I always see the dependencies as other classes, like services. But an object may depend, heavily and/or crucially in fact, on configuration values such as Strings and resource wrappers (File/Path/URI/URL, as opposed to an entire big value string/document, or a reader).
Note, this is about the DI design pattern in Java or C# syntax alone, not how any particular DI framework handles this.
For example, let's say I have this class which returns a String (relative path, based on some obscure implementation logic). It (rather its various implementors) has a configuration/initialization dependency on the "projectLocation", as a user could have various projects on their machine and this class will perform some logic based on a given project whenever it is called.
public abstract class PathResolver {
protected File projectFilesLocation;
public RoutinePathResolver(File projectFilesLocation) {
this.projectFilesLocation = projectFilesLocation;
}
public abstract String getPath(String someValue);
}
I am not using DI just for unit-testing (gasp I'm not even unit testing, existing project). I just want to separate my dependency/creational concerns and logic concerns period.
Provided that the thing you want to inject, e.g., a file location, is something that would be directly used by the class then it is perfectly valid to inject it.
In the case of an Object such as a File or a String then this is no different to something called Service. It is a dependency of your class thus DI applies.
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.
I'm working on a project that's using the MS Application Blocks. I see the 'Unity' dll is available to me. It's version 1.1 by the way. How can I use dependency injection here?
I have a class
public class ScheduleDataDetailsDC
{
public int ScheduleID;
public List<ScheduleRateLineItem> MinRateList;
public List<ScheduleRateLineItem> MaxRateList;
public List<ScheduleRateLineItem> VotRateList;
public List<ScheduleLOSRateDC> LosRateList;
public List<ScheduleRateParamsDC> RateParams;
}
So when I new it up I am doing this...
new ScheduleDataDetailsDC{
LosRateList = new List<ScheduleLOSRateDC>()
, MaxRateList = new List<ScheduleRateLineItemDC>()
, MinRateList = new List<ScheduleRateLineItemDC>()
, RateParams = new List<ScheduleRateParamsDC>()
, VotRateList = new List<ScheduleRateLineItemDC>()
}
Can Unity 1.1 Help me in anyway here? I would like to just be able to use var x = new ScheduleDetailsDC(), and those 5 inner lists be initialized for me. Can Unity do anything for me here? Please note I've never used DI before.
Thanks for any pointers,
~ck in San Diego
The best thing to do would be to initialise the lists in the constructor and deny direct access to them from other classes by making them into properties:
public class ScheduleDataDetailsDC
{
public ScheduleDataDetailsDC()
{
this.MinRateList = new List<ScheduleRateLineItem>();
//inialise other lists
}
public List<ScheduleRateLineItem> MinRateList { get; private set; }
...
}
It doesn't seem as though dependency injection can really be of use here since the class seems to be a simple data container, although it's difficult to tell without more context.
Yes Unity can help you, but I think it's not the case. You can just initialize your lists incide your object giving them default instances, Unity as any other IoC container shouldn't be used as a simple object builder (despite it could).
I'm not sure specifically what the details of the 1.1 release of Unity are, but generally speaking whenever you are using an Inversion of Control Container, you have to go through the following steps:
Register the types your IoC container (Unity in your case) knows about. This includes all of the main types that you plan to request, plus all of the dependent types. In your case you will need to let it know about ScheduleDataDetailsDC, and what, exactly needs to go into each of the lists that are considered dependencies
Your types should specify all of the required dependencies as constructor arguments. This is what the IoC Container will look at to determine what needs to be injected. If you have optional dependencies then you can use Property Injection to support that (if your IoC container supports it, which I think Unity does)
You must request an instance of your registered type from the container. How exactly you do this depends on you container. There should be a method like Get<T>() or Resolve<T>. Generally your going to request instances of the "Highest Level" classes, i.e the ones that are used somewhere near the entry point for your software. If you do this, and you have applied Dependency Injection for all dependent classes down the line (and you've correctly registered all of the dependent types) you should get an object with all of it's dependencies supplied, and likewise all of that objects dependencies should be supplied, and on down the line.
You also tend to see Interfaces used in conjunction with IoC a lot since you can bind a concrete type to the interface type, and then specify that interface as your dependency. This allows you to apply business rules and configuration values during the binding process that will give you the ability to use different concrete implementations in cases where you would need to do such a thing.
So given all of this, it's hard to say exactly what would be involved in utilizing Unity in the situation you've outlined above. Firstly you would need to register ScheduleDataDetailsDC, but to get the dependencies in place you would also need to register each of the List types, or more specifically each concrete object that would go in each list (and then, of course all of the dependencies for those classes). Since I'm not really sure what the roles of those lists are, it's hard for me to say how you could go about doing that (or even if you could go about doing that).