Multiple Decorator pattern in castle-windsor - c#

We are in the process of redesigning some legacy software to be more testable and have decided upon Dependency-Injection and Castle.Windsor to help us.
First, our goal:
* A number of decorators that all work on a data stream.
* Multiple combinations of the decorators are possible and the root nodes in each case can be required to get data from different places.
Technically, our design is as follows:
interface IUpdateableValue<T>
{
T Get();
};
We have e.g. three sets of data to be retrieved with a number of components, all implementing IUpdateableValue() (Pseudo-code):
JsonParser(
Decompressor(
Decrypter(decryptionKey
FileCache(filename,
HttpWebDownloader(url))))
XmlParser(
Decompressor(
Decrypter(decryptionKey2
FileCache(filename2,
HttpWebDownloader(url2))))
I'm having trouble getting out design to fit into a DI-framework like Castle-Windsor. I suspect some of it could be handled by named instances, but this seems smelly for this usage.
The idea is that the "user" of e.g. the JsonParser and XmlParser instances don't know (or care) whether data comes from a HttpUrl, a file or magically pulled out of a hat.
I'm thinking there is something wrong in our design, but unsure how to fix it.
Any ideas on how to progress?

With Castle Windsor you can implicitly configure decoraters by registering them in the correct order. You need to register the outer decorater first:
container.Register(Component
.For<IUpdateableValue>()
.ImplementedBy<JsonParser>());
container.Register(Component
.For<IUpdateableValue>()
.ImplementedBy<Decompressor>());
container.Register(Component
.For<IUpdateableValue>()
.ImplementedBy<Decrypter>());
...
When you resolve IUpdateableValue Caste Windsor will automatically wire up the dependencies, so they are nested correctly.

Related

How do you configure registration lifetimes/settings using types in Autofac?

I have different Interfaces which are supposed to describe the registration of services.
So far I only had two variations
public interface ISingletonElement {}
public interface ITransientElement {}
Which was easy enough to just have two different registrations like
builder
.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.AssignableTo<IService>()
.AssignableTo<ISingletonElement>()
.AsImplementedInterfaces()
.SingleInstance();
builder
.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.AssignableTo<IService>()
.AssignableTo<ITransientElement>()
.AsImplementedInterfaces()
.InstancePerDependency();
But lets say I want to have a more precise description with interfaces like
public interface IAutowiredElement {}
I obviously could just have more registration blocks. But that would get messy really fast.
// ..
.AssignableTo<IService>()
.AssignableTo<ISingletonElement>()
.AssignableTo<IAutowiredElement>()
// ..
.AssignableTo<IService>()
.AssignableTo<ISingletonElement>()
.Except<IAutowiredElement>()
// and so on ..
So my idea was to do something like
// pseudo code
builder
.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.AssignableTo<IService>()
.Do(e => {
if (e is IAutowiredElement)
{
e.PropertiesAutowired()
}
if (e is ISingletonElement)
{
e.SingleInstance()
}
// ...
});
I agree with the comments that if you're going to use code-based metadata to indicate registration information that attributes are a better choice. The point of attributes is to carry type metadata around; marker interfaces aren't generally a good idea for that sort of thing.
A quick Google search on 'autofac attribute based registration' pulls up a nice library that someone has written that does what it appears you're looking for. There are people out there trying to do what you're describing; I'd recommend not reinventing the wheel if you can avoid it.
That said, there are reasons Autofac doesn't ship with attributes out of the box and they're something to consider as you build up your solution:
Changing the lifetime scope of a component shouldn't require you to change the component. Adding the attribute to the component itself means the person consuming the component doesn't get to make the choice about how they use it. What if you mark it as a singleton but the consumer needs it to be used one instance per web request? How do they change that?
Dependency injection frameworks / inversion of control containers should generally only be at the "composition root" of your application. That's basically the app startup class. Accessing the container or spreading DI-specific metadata through the app isn't generally considered good practice. It makes the code far less portable and usable.
Regardless, if you still choose to go with an attribute-based solution, I'd recommend trying to find something out there that exists, even if you fork it and start from there.

Looking for best way to refactor a large class

I have a situation whereby a predecessor has created a class that is designed to handle the creation of Note entities that are added to the database to journal actions that are carried out by the system across the site.
At present, this class has been broken down into several CreateXYZNote methods that take an enum denoting a specific note type, and an instance of the model that drives that area of the site.
My problem is, there are so many types of notes, each used only in one or two places across the system. Each of the methods is huge, consisting of a small amount of common code, and specifics (e.g. the textual content of the note) are held within a series of switch statements based on an enum. Extremely hard to find the code relating to specific notes, and very hard to maintain at present, and it's only going to grow as new types of notes find their way into the system over time.
Has anyone got any advice or patterns that could help with this sort of situation?
The simplest solution I can think of is that I have a set of profiles held outside of this class as a dictionary (keyed by the enum values) that define the title, description, categories etc. for the notes, and this class then becomes just a means of looking up those values and creating the note, but it just feels like I'm moving the problem to another place rather than resolving it.
You could use a NoteFactory that has a INote Create(NoteType type) method. The factory could depend on a Dictionary keyed by NoteType that the factory uses to find and return the appropriate Note. This way you avoid a non-OCP switch statement.
The factory can be injected with the dictionary, using an IoC container helps here, or you can create the dictionary in the constructor.

How to use MEF to allow plugins to override existing functionality?

I'm using MEF to allow users to extend my C# library. It's working great so far, but right now I'm trying to use it in a way I haven't seen it used before.
The primary use case for MEF I've seen so far is this:
Application exposes primitive interface (IPerson)
External library uses MEF and primitive interfaces to extend functionality of main library (e.g. IPoliceman : IPerson, adds functionality)
Application then uses ImportMany to search for correct IPerson depending on what it must do
But I need something like this: Let's say I have a tax calculator that takes a bunch of parameters and returns estimated tax depending on those parameters. I want users to be able to create plugins with MEF that modify how those calculations are done. Only one plugin that does this should be able to be loaded at any one time. Otherwise, how do I decide which alternate implementation to use?
So basically, my question boils down to this: Usually MEF allows adding implementations of classes and methods. How do I use it to allow users to replace an implementation?
Normally when you try to override an export which is already present in the application, you will get a cardinality exception for an [Import(typeof(IFoo)] because MEF expects exactly one matching export to be available.
However, you can put your plugins in a separate export provider and give it priority. Here I do that for a "plugins" subfolder inside the application folder:
Assembly executingAssembly = Assembly.GetExecutingAssembly();
string exeLocation = Path.GetDirectoryName(executingAssembly.Location);
string pluginPath = Path.Combine(exeLocation, "plugins");
var pluginCatalog = new DirectoryCatalog(pluginPath);
var pluginExportProvider = new CatalogExportProvider(pluginCatalog);
var appCatalog = new DirectoryCatalog(exeLocation,"*");
var appExportProvider = new CatalogExportProvider(appCatalog);
var container = new CompositionContainer(
pluginExportProvider, appExportProvider);
pluginExportProvider.SourceProvider = container;
appExportProvider.SourceProvider = container;
The order of the export providers as passed to the composition container determines the priority: if an export is provided by both the plugins and the application parts, then the plugins will get priority.
What you're talking about is actually just a different way of looking at the same problem. The answer is simpler than it sounds - for any behavior that you want a client to be able to override, just put that behavior in a plugin.
There's nothing that says you can't write plugins just because you're the author of the application. Put your TaxCalculator class in a plugin, and expose an interface allowing users to write their own tax calculators. At runtime, if you have more than one loaded, favor the one that isn't yours. Out-of-the-box, you will be using your tax calculator plugin, so it will work exactly the way you expect. If the user creates their own tax calculator plugin and drops it in the right directory, you use it instead, effectively allowing them to "override" your original functionality.
I'm not sure how much sense is going to make, but let me try.
I would make a TaxCalculatorManager class. That class could load all of the ITaxCalculator implementations from MEF. From there, you could have something in the Export attribute that would allow ranking of the implementations. Then when you need to calculate the taxes, you would call TaxCalculatorManager.Calculate which would rank the ITaxCalculator implementations and call Calculate on the winner.
Let me know if you need me to clarify any points.

Constructor injection overuse

I am looking for best practices of avoiding constructor injection overuse. For example I have Meeting entity which has few sub entities like shown below:
Meeting
MeetingContacts
MeetingAttendees
MeetingType
Address
MeetingCompanies
MeetingNotes
MeetingService class looks like below:
public class MeetingService
{
private readonly IMeetingContactRepository _meetingContactRepository;
private readonly IMeetingAttendeeRepository _meetingAttendeeRepository;
private readonly IMeetingTypeRepository _meetingTypeRepository;
private readonly IAddressRepository _addressRepository;
private readonly IMeetingCompanyRepository _meetingCompanyRepository;
private readonly IMeetingNoteRepository _meetingNoteRepository;
private readonly IMeetingRepositoy _meetingReposity;
public MeetingService(IMeetingRepositoy meetingReposity, IMeetingContactRepository meetingContactRepository, IMeetingAttendeeRepository meetingAttendeeRepository,
IMeetingTypeRepository meetingTypeRepository, IAddressRepository addressRepository,
IMeetingCompanyRepository meetingCompanyRepository, IMeetingNoteRepository meetingNoteRepository)
{
_meetingReposity = meetingReposity;
_meetingContactRepository = meetingContactRepository;
_meetingAttendeeRepository = meetingAttendeeRepository;
_meetingTypeRepository = meetingTypeRepository;
_addressRepository = addressRepository;
_meetingCompanyRepository = meetingCompanyRepository;
_meetingNoteRepository = meetingNoteRepository;
}
public void SaveMeeting(Meeting meeting)
{
meetingReposity.Save();
if(Condition1())
_meetingContactRepository.Save();
if(Condition2())
_meetingAttendeeRepository.Save();
if(Condition3())
_meetingTypeRepository.Save();
if(Condition4())
_addressRepository.Save();
if(Condition5())
_meetingCompanyRepository.Save();
if(Condition6())
_meetingNoteRepository.Save();
}
//... other methods
}
Here are just seven dependencies but real code contains much more of them. I used different techniques described in the "Dependency Injection Constructor Madness" but I have not found how to deal with repository dependencies.
Is there any way how I can reduce the number of dependencies and keep the code testable?
Constructor overuse is just a symptom - it seems you are approximating a unit of work by having a "master" class that knows about the various elements of message persistence and plugs them into the overall save.
The downside is that each repository communicates its independence of the others by exposing a dedicated Save method; this is incorrect, though, as SaveMeeting explicitly states that the repositories are not independent.
I suggest identifying or creating a type that the repositories consume; this centralizes your changes and allows you to save them from a single place. Examples include DataContext (LINQ to SQL), ISession (NHibernate), and ObjectContext (Entity Framework).
You can find more information on how the repositories might work in a previous answer of mine:
Advantage of creating a generic repository vs. specific repository for each object?
Once you have the repositories, you would identify the context in which they would act. This generally maps to a single web request: create an instance of the common unit of work at the beginning of the request and hand it to all the repositories. At the end of the request, save the changes in the unit of work, leaving the repositories free to worry about what data to access.
This neatly captures and saves everything as a single unit. This is very similar to the working copy of your source control system: you pull the current state of the system into a local context, work with it, and save the changes when you're done. You don't save each file independently - you save them all at the same time as a discrete revision.
To expand a little bit on my comment above:
Since this question is directed towards how to manage repository dependencies, I have to assume that the MeetingService is managing some sort of persistent commit. In the past, when I have seen classes like MeetingService with that many dependencies, it is clear they are doing too much. So, you have to ask yourself, "what is my transaction boundary". In other words, what is the smallest commit that you can make that means that a meeting has been successfully saved.
If the answer is that a meeting is successfully saved after a call to meetingReposity.Save(); then that is all that MeetingService should be managing (for the commit).
Everything else is, essentially, a side effect of the fact that a meeting has been saved (notice that now we are speaking in the past tense). At this point, event subscription for each of the other repositories makes more sense.
This also has the nice effect of separating the logic in all of the conditions into subscriber classes that follow SRP to handle that logic. This becomes important when the logic of when the contact repository commits goes through a change, for example.
Hope this helps.
Each of the first three answers give important suggestions and ideas for dealing with the problem in the abstract. However, I may be reading too much into your example above, but this looks like a problem of too many aggregate roots, not too many dependencies per se. This has to do with either a lack in the persistence mechanism underlying your repository injection infrastructure, or a misconfiguration of the same.
Simply, the Contacts, Attendees, Notes, &c. should be composite properties of the Meeting itself (if only as links to separately managed Contact, &c. objects/data); therefore, your persistence mechanism should be saving them automatically.
Heeding Bryan Watts' adage that "constructor overuse is just a symptom," a couple of other possibilities:
Your persistence mechanism should be handling persistence of the Meeting graph automatically, and is either misconfigured or lacks the capability to do this (all three that Bryan suggests do this, and I would add DbContext (EF 4.1+)). In this case, there should really only be one dependency--IMeetingRepositoy--and it can handle atomic saves of the meeting and its composites itself.
SaveMeeting() is saving not just links to other objects (Contacts, Attendees, &c.) but is also saving those objects as well, in which case I would have to agree with dtryon that MeetingService and SaveMeeting() are doing far more than the names imply, and his mechanism could alleviate it.
Do you really need the repository functionality to be split into that many interfaces? Do you need to mock them separately? If not, you could have fewer interfaces, with more methods.
But let's assume your class really needs that many dependencies. In that case you could:
Create a configuration object (MeetingServiceBindings) that provides all the dependencies. You could have a single configuration object per whole module, not just single service. I don't think there's anything wrong with this solution.
Use a Dependency injection tool, like NInject. It's quite simple, you can configure your dependencies in code in one place and don't need any crazy XML files.

What is an IOC container actually doing for me here?

So I've refactored completely to constructor injection, and now I have a bootstrapper class that looks similar to this:
var container = new UnityContainer();
container.RegisterType<Type1, Impl1>();
container.RegisterType<Type2, Impl2>();
container.RegisterType<Type3, Impl3>();
container.RegisterType<Type4, Impl4>();
var type4Impl = container.Resolve((typeof)Type4) as Type4;
type4Impl.Run();
I stared at it for a second before realizing that Unity is really not doing anything special here for me. Leaving out the ctor sigs, the above could be written as:
Type1 type1Impl = Impl1();
Type2 type2Impl = Impl2();
Type3 type3Impl = Impl3(type1Impl, type2Impl);
Type4 type4Impl = Impl4(type1Impl, type3Impl);
type4Impl.Run();
The constructor injection refactoring is great and really opens up the testability of the code. However, I'm doubting the usefulness of Unity here. I realize I may be using the framework in a limited manner (ie not injecting the container anywhere, configuring in code rather than XML, not taking advantage of lifetime management options), but I am failing to see how it is actually helping in this example. I've read more than one comment with the sentiment that DI is better off simply used as a pattern, without a container. Is this a good example of that situation? What other benefits does this solution provide that I am missing out on?
I have found that a DI container becomes valuable when you have many types in the container that are dependent on each other. It is at that point that the auto-wire-up capability of a container shines.
If you find that you are referring to the container when you are getting object out of, then you are really following the Service Locator pattern.
To some extent you're right. Inversion of control does not need to mean using IoC container at all. If your object graph is small enough and convenient enough to be created at once in some kind of bootstrapping code, that's inversion of control, too.
But using an IoC tools simplifies the object creation in case of more complex scenarios. Using IoC tools you can manage object lifecycles, compose your object graph from different configurations or when not the whole graph is known at compile time, easily defer the object creation etc. etc.
There is no general solution. Everything depends from your specific needs. For a simple project with few classes, using IoC can be more annoying than helpful. For a big project I can't even imagine how the bootstrapping code need to look like.
See my post here for an extensive response to this question.
Most of the other answers here are correct, and say pretty much the same thing. I would add that most IoC containers allow you to auto-bind types to themselves, or use binding by convention. If you set up Unity to do that, then you can get rid of all that binding code entirely.
The difference is that you are doing the dependency injection instead of Unity doing dependency injection. In your example, you would have to know what types need to be created coupling your code to those types. You now need to know in your code that Impl1 should be created whenever you need a Type1.
Here's a simple code illustration of what other's have said (albeit taking a few liberties, property injection instead of constructor injection and assuming you've registered your types, etc).
public interface IFoo { }
public interface IBar { IFoo FooImpl { get; set; } }
public interface IBaz { IBar BarImpl { get; set; } }
public interface IBat { IBaz BazImpl { get; set; } }
As your object graph grows and dependencies are nested further and further down the graph, you'll have to provide the whole tree:
var bat = new Bat{
BazImpl = new BazImpl() {
BarImpl = new BarImpl() {
FooImpl = new FooImpl()
}
}
};
However, if you use the container correctly, all of that resolution comes based on what you've registered:
var bat = container.Resolve<IBat>()
Much like the other answers have probably stated, an IoC container is not required to perform dependency injection. It simply provides for automated dependency injection. If you don't get much of an advantage from the automation, then don't worry too much about a container, especially at the entry point of your application where you're injecting the initial objects.
There are however some things an IoC can make easier:
Lazy initialization. Autofac and a few others (not sure about Unity) can detect a constructor that takes a Func<IMyDependency> and, given a registration for an IDependency, will automatically generate the appropriate factory method. This reduces the front-loading often required in a DI system, where a lot of big objects like repositories have to be initialized and passed into the top-level object.
Sub-dependency hiding. Say class A needs to instantiate a class B, and B needs C, but A shouldn't know about C. Maybe even class Z which created A can't even know about C. This is the thing for which IoCs were created; throw A, B and C into the container, shake it up and resolve a fully-hydrated B to give to A, or a factory method which can be injected into A (automatically) and which the A can use to create all the B references it wants.
Simple "singletoning". Instead of creating and using a static singleton, an IoC can be told to create and return one and only one instance of any registered dependency no matter how many times that dependency is asked for. This allows the developer to turn any ordinary instance class into a singleton for use in the container, with no code change to the class itself required.
Your example is very simple, and the object graph would be very easily managable without using a DI framework. If this is really the extent of what is needed, doing manual DI would work fine.
The value of using a DI framework goes up very quickly as the dependency graph becomes more complex.

Categories

Resources