Currently I'm developing two solutions (first for country A, second for country B), which are very similar. I'm using wpf, c#, mvvm, sql server.
Some of modules are identical in every solution, some of them are partially different (ex. some classes have additional fields or methods), and some are completely different (ex. VAT module). For me, developing completely independent solutions is not the best solution (time cost).
So, I was thinking of creating two solutions (A and B) which will contain only main screen where would I prepare user interface. Then, in third solution (C) I would have project (=modules) and link them from A or B.
If module is identical for both version - no problem. If it is completely different - ok, I must develop it independently. But, the question is how to design modules which are slightly different?
Should I use abstract factory design pattern and put in AbstractProduct everything that is identical, and in ConcreteProducts put additional fields/methods? For WPF forms I can't use this pattern - I must develop a form for every version.
Thx.
what you really want to use is Dependency injection.
First you create an Interface then have your concrete impls implement this interface per country.
interface ISolution
{
....
}
class CountryA : ISolution{
...
}
class CountryB : ISolution{
...
}
Then register these Interface to impl mapping at composition root.
private static IContainer ConfigureDependencies() {
return new Container(x =>{
x.For<ISolution>().Use<CountryA>();
});
}
Then you ask the container to give you an instance of ISolution. and it will provide you the correct impl.
You can do the same for CountryB.
You can have auto wiring or late binding, something more dynamic. and you can switch impls.
Take a look at structuremap for examples.
Related
I ran at a major architectural problem.
CONTEXT
I'm trying to build an ASP.NET Core microservice application that implements the strategy pattern.
The application communicates with other microservices.
I have a main entity that aggregates all the information I need to work with, let's call it "MainContext". The goal is that this entiy is loaded and built only one time (as we need to get that information from other microservices) and then is processed throughout the whole application.
public class MainContext
{
public DeterminerAttribute Attribute {get; set; }
public OtherContextA ContextA { get; set; }
public OtherContextB ContextB { get; set; }
}
As you can see, the MainContext aggregates other contexts. These 'OtherContexts' are base classes that have their own child classes. They are somehow different and have different types and quantities of fields.
The application builds the MainContext in one separate place. The process looks something like this:
We get a specific attribute from other microservice and use this attribute as a determiner in a switch expression. The attribute is also saved in MainContext.
In switch expression we load specific implementations of OtherContextA and OtherContextB classes and wrap them up in their base classes. This step is important, as I don't want to ask for information that I don't need from other services.
The method returns MainContext with all information loaded, ready to use.
Then, I use strategy pattern, because different contexts require different treatment.
THE PROBLEM
The strategies have the same interface, and thus should implement the same methods that have the same signature. In my case, there is only one method, that looks something like this:
public class SomeStrategyToProcessContext : StrategyInterface
{
public async Task ProcessContext(MainContext mainContext, ...);
}
Now, in strategies I want to work with concrete implementations of Contexts. It makes sense as I KNOW, as a programmer who made that mess, that the strategies to be used are chosen based on the same attribute that I used to load contexts and therefore should work with the concrete implementations, as I need data stored in them. But this:
var concreteContext = (OtherConcreteContextA) mainContex.ContextA
is considered a bad pratice, AFAIK.
Obviously, base classes have only base, unspecific data. In strategy classes, I want to provide access only to the NEEDED data, no more, no less.
My quistion is: is there any safe and sustainable way of implementing this witin OOP (or other) paradigm? I want to avoid the casting, as it breaks the abstraction and contradics every programming principle I've learned about. Any advice, even if it's toxic or/and suggests to change the whole architecture is as good as gold. Thanks!
I come across this regularly when refactoring code. Say I have a base class and I read some configuration parameters and stuff them into properties like this
public BaseClass()
{
_property1 = ConfigurationManager.AppSettings["AppSetting1"];
_property2 = ConfigurationManager.AppSettings["AppSetting2"];
_property3 = ConfigurationManager.AppSettings["AppSetting3"];
}
And then I call a method in another class like this
OtherClass otherClass = new OtherClass();
var foo = otherClass.SomeMethod(_property1, _property2, _property3);
Is it better to do that? What if I only needed the AppSettings values inside of the OtherClass class? then I could just load them up as private props and initialize them in the constructor and the referencing class/caller wouldn't need to be concerned with the settings.
public OtherClass()
{
_property1 = ConfigurationManager.AppSettings["AppSetting1"];
_property2 = ConfigurationManager.AppSettings["AppSetting2"];
_property3 = ConfigurationManager.AppSettings["AppSetting3"];
}
My implementation would then simply be
OtherClass otherClass = new OtherClass();
var foo = otherClass.SomeMethod();
This one bugs me but I am not really sure why. Which is a better practice and why? And I apologise I am missing something obvious. It happens sometimes lol.
Thanks -Frank
In my view, it depends on what goal of your class.
If class belongs to domain classes, so there is no need to have a dependency to ConfigurationManager class. You can create a constructor and supply necessary data:
public class FooClass()
{
public Property1 {get; private set;}
public FooClass(string property1)
{
Property1 = property1;
}
}
If FooClass belongs to Service Layer, then, in my view, it is eligible to have a dependency to ConfigurationManager class.
I can't really comment on "better" as that's quite subjective, but it's at the very least factual to say that passing the parameters into the method, rather than having the method go and get them itself, is a form of dependency injection. Dependency injection has advantages in that it reduces the number of things the class has to know how to do/reduces the number of other classes any given class needs to do its work. Typically in OO design we look for ways to reduce the dependencies a class has on other classes. You might also see the concept referred to in general as low coupling. Classes that are not highly coupled to other classes are easier to reuse as independent modules within multiple programs
In your example, OtherClass (and/or BaseClass) needs to know what a ConfigurationManager is, which means it needs a reference to its namespace, needs to have system.configuration.dll available on the target etc just so that it can go and get some basic things (strings) that contain info necessary to do its work. If you instead give the strings to the method then it can do its work without knowing what a ConfigurationManager is - you can use it in an app that doesn't even have a ConfigurationManager anywhere, maybe because it gets its config from a database or perhaps it's part of a unit test that gets some contrived data directly from hard coding to ensure a given result is always obtained
When you're down with the concept that the data a class needs to do its work can come from above it starts to make more sense why systems that pass data around like this can work with an inversion-of-control container; essentially software that creates instances of objects for you according to some preconfigured rules about where to get the data that should be passed in. An IoC container can look at an object and decide what arguments to pass to (e.g. its constructor) based on a consistent set of rules, and take another step towards removing dependencies by further reducing use of the word "new". Think of it like writing a config file to describe which of your objects need what instances of other classes to do the work. You craft your IoC container setup so it makes one IniFileConfigSettingsProvider instance and then provides that instance to any object that needs some kind of IConfigSettingsProvider to do its work. Later you switch away form ini files and go to Xml files. You create a class called XmlFileConfigSettingProvider, register it with the IoC and it becomes the new instance that is passed to any class needing an IConfigSettingsProvider. Critically, you made another class, registered it with the IoC and then it gets used throughout your program but you never made an instance of it yourself
If you ever heard the phrase "new is glue" concepts like this are generally what it alludes to - when your OtherClass says var x = new ConfigurationManager... x.Settings["a"].... the use of the word new has suddenly hard wired it to needing a ConfigurationManager; it can't function without knowing what it is. The strive these days is generally to have a class accepting a "passed-in provider of settings that complies with some interface" or "passed-in primitives that are settings" - things that are either implementation specific but obey a generic interface, or ubiquitous in the language and need no special imports respectively. Perhaps either of your mentioned approaches bug you because deep down you feel that neither of them need to depend on ConfigManager; whether they both need settings or not, they can get them passed in, from something higher up the chain that should be making the decisions as to what settings to use
There will be pros and cons of every design and coding choice. As they say, same pattern may not fit everyone. So one has to customize based on need.
Mainly, decision should be based on use cases of your application. Let me provide few scenarios to describe it. Suppose items configured in AppSettings will not change in life-time of the your application then you can have an approach in which dependencies with AppSettings are least. In particular an approach as var foo = otherClass.SomeMethod(_property1, _property2, _property3);. This matches with OOD principles as classes will focus on business logic.
But if you see add/modifying/deleting items (even in rare situations) during life time then above approach would be difficult to maintain. For example without restarting your application/WebServer if AppSettings needs to be reloaded based on certain conditions. One may argue why such settings will be kept in AppSettings, which is very valid too. If your application demands such scenarios then it would be better to use ConfigurationManager.AppSettings without worrying about dependencies. One can opt to extend it have wrapper class (Singleton pattern) to manage and provide access to ConfigurationManager.AppSettings.
I have a class A that depends on 10 other classes. According to Dependency Injection pattern, i should pass all dependencies of A by its constructor.
So lets assume this constructor (of course this is not a working or real code, since I am not allowed to post the real code here)
public ClassA(ClassB b, ClassC c, ClassD d, ClassE e, ClassF f, ClassG g, ClassH h, ClassI i) {
this.b = b;
this.c = c;
this.d = d;
this.e = e;
this.f = f;
this.g = g;
this.h = h;
this.i = i;
}
I have read on Martin Fowler's book about refactoring that having a method with a lot of parameters is a code smell and should not happen.
My question is: is this OK when we are talking about DI? Is there a better way of inject dependencies without breaking Martin Fowler's rules?
I know I could pass the dependencies through properties, but that may cause errors since no one is really sure what should be pass in order that the class works.
EDIT
Thanks for all your answers. I will try now to demonstrate some of class A dependencies:
1 - A class to access a DB
2 - Another class to access another DB (yes, i need to perform operations on two databases)
3 - A class to send error notifications by email
4 - A class to load configurations
5 - A class that will act as timer for some operations (maybe this one can be avoided)
6 - A class with business logic
There any many others that i am trying to get rid of, but those are really necessary and I dont see any ways of avoiding them.
EDIT
After some refactoring now i have 7 dependencies (down from 10). But I have 4 DAO objects:
CustomerDAO
ProcessDAO
ProductsDAO
CatalogDAO
Is it correct do create another class called MyProjectDAO and inject those DAOS onto it? This way I will have only one DAO class that aggregates all DAO objects of my project. I dont think this is a good idea because it violates the Single Responsibility Principle. Am I right?
In my experience:
Try to design your class so it needs fewer dependencies. If it needs that many, it may have too many responsibilities.
If you're really convinced that your class design is appropriate, consider whether it may make sense for some of those dependencies to be joined together (e.g. via an adapter which takes responsibility for one "big" operation your class needs by delegating to a few of the dependencies). You can then depend on the adapter instead of the "smaller" dependencies.
If every other bit really makes sense, just swallow the smell of having a lot of parameters. It happens sometimes.
Can you justify (to yourself) why the class depends on 10 other classes? Are there member variables you use to tie together a subset of those classes? If so, that indicates that this class should be broken up so that the extracted class would depend on the subset and the variables that tie such state together goes in the extracted class. With 10 dependencies, it's possible that this class has simply grown too large and needs to have its internals broken up anyway.
A note regarding your final sentence: such order dependency can also be a code smell, so it's probably good not to expose it in your interface. In fact, consider whether or not the order requirements are because operations need to be carried out in a specific order (it is the complexity of the algorithm or protocol), or because you've designed your classes to be inter-dependent. If the complexity is due to your design, refactor to eliminate the ordered dependency where possible.
If you cannot refactor (the complexities are all essential and you just have a terrible coordination problem on your hands), then you can abstract the ugliness and keep users of this class shielded (builder, factory, injector, etc).
Edit: Now that I have thought about it, I am not convinced that essential complexities of your algorithm or protocol cannot be abstracted a bit (though that might be the case). Depending on your specific problem, similarities in the manipulations of those dependent classes might either be better solved with the Strategy pattern or the Observer pattern (event listeners). You might have to wrap these classes in classes that adapt them to slightly different interfaces than what they currently expose. You'd have to evaluate the tradeoff of having the code in this monster class become more readable (yay) at the expense of up to 10 more classes in your project (boo).
I'd also like to make an addendum to abstracting the construction of this class. It seems important that any class that depends on this class also use the Dependency Injection pattern. That way, if you do use a builder, factory, injector, etc. you don't accidentally rob yourself of some of the benefits of using the DI pattern (the most important in my mind is the ability to substitute mock objects for testing).
Edit 2 (based on your edit):
My first thought is "what, no logging dependency?" :)
Even knowing what the dependencies are, it's difficult to offer useful advice.
First: what are the responsibilities of everyone? Why does this class depend on controller code (the business logic) and on Model code (two different database access classes, with DAO classes)?
Depending both on DAOs and DB access classes is a code smell. What is the purpose of a DAO? What is the purpose of the DB classes? Are you trying to operate at multiple levels of abstraction?
One of the principles of OO is that data and behavior get bundled into little things called classes. Have you violated this when you created this business logic class distinct from the objects it manipulates distinct from the DAO distinct from this class? Related: Take a brief diversion into SOLID.
Second: A class to load configurations. Smells bad. Dependency Injection helps you identify dependencies and swap them out. Your monster class that depends on certain parameters. These parameters are grouped into this configuration class because...? What is the name of this configuration class? Is it DBparameters? if so, it belongs to the DB object(s), not to this class. Is it generic like Configurations? If so, you've got a mini dependency injector right there (granted, it is probably only injecting string or int values instead of composite data like classes, but why?). Awkward.
Third: The most important lesson I learned from Refactoring was that my code sucked. Not only did my code suck, but there was no single transformation to make it stop sucking. The best I could hope for was to make it suck less. Once I did that, I could make it suck less again. And again. Some design patterns are bad, but they exist to allow your sucky code to transition to less sucky code. So you take your globals and make them singletons. Then you eliminate your singletons. Don't get discouraged because you've just refactored to find that your code still sucks. It sucks less. So, your Configuration loading object may smell, but you might decide that it isn't the smelliest part of your code. In fact, you may find that the effort to "fix" it isn't worth it.
Yes - a method taking this many parameters should be considered a code smell. Is this method truly only doing one thing and one thing only?
If this is still true you can still lower the number of dependencies by looking at the relationships between the dependencies - are any of them closely related, could they be coupled into aggregate dependencies? E.g. you could refactor by creating a new class K that uses A, B and C internally (injected into class K by constructor, then using composition) - so the number of parameters to the method would be reduced by two.
Rinse and repeat until aggregating doesn't make sense anymore and/or you have a reasonable number of parameters.
Also see a related blog post: "Refactoring to Aggregate Services"
I'd also advise to redesign your application. In case it is not possible you can pass your IoC container as a constructor parameter. If you do not want to couple your code with a concrete implementation you can always abstract it. The code will look something like this.
public interface IAbstractContainer
{
T Resolve<T>();
}
public class ConcreteContainer: IAbstractContainer
{
private IContainer _container; // E.g. Autofac container
public ConcreteContainer(IContainer container)
{
_container = container;
{
public T Resolve<T>()
{
return _container.Resolve<T>();
}
}
public classA(IAbstractContainer container)
{
this.B = container.Resolve<ClassB>();
this.C = container.Resolve<ClassC>();
...
}
}
A ConcreteContainer instance is injected the usual way.
I am developing a kind a translator from language A to B (yeah, it kinda is like a compiler). A translation is generally from several different files and each one of them has the same 3 sections to translate. So, the way I did it, I kind of have it the following way:
When I instantiate a translator and give it some data, it will need to generate all the needed FileTranslator classes. As I shouldn't do the new in Translator, I should ask for a factory from above. The same happens in the Sections translators. This poses the problem that I'm forced to create a lot of boilerplate factories. Moreover, each one of the translators might need even more factories to generate some other classes they might want to use.
Am I thinking this the wrong way or is it just the way it is? I am not allowed to use any kind of DI/IoC framework in this project, btw.
Edit:
I'm afraid I am not getting my message get sent across.
In this specific case, as my Translator class needs to be able to generate at any moment some FileTranslator, it would need a FileTranslatorFactory. I know I can have an IoC Container do the wiring for me, but the IoC Container in itself will not save me for the problem of having to code up the code of the FileTranslatorFactory itself. Am I right?
Now, the problem is that a FileTranslator will also have to be able to generate whenever it needs SectionATranslators, SectionBTranslators and SectionCTranslators (and do not think they are any similar because their names are -- they are totally different and have nothing to do with each other!). So I'd have to define factories for each one of them. So for such a simple 5 classes system, I'd need to create 4 (!!!) factories.
Being that I don't want my domain objects to depend on an IoC-Container and that I don't want to have a single factory for all the 4 kinds of objects that seem to need one, am I still missing something?
The fact that there is a lot of boilerplate code involved in handcranking DI for class hierarchies like this is WHY the frameworks exist. Sorry, but unless you can get whoever decided on the no DI/IoC frameworks rule to change their mind, you are either going to be writing lots of boilerplate code, or you will end up writing a framework yourself.
EDIT - with a completely fictitious framework, to keep this as agnostic as possible, but explaining how you can eliminate all but one call into the container in many scenarios.
So, with an implementation of Translator like:
public class Translator
{
private ITranslator translatorInstance;
public Translator()
{
SomeContainer container = SomeContainer.CreateFromConfig(configFilePath);
// this is the ONLY point we touch the container
translatorInstance = container.GetMeA<ITranslator>();
}
// implementation
}
We can see that this works as a factory, and is the only class that needs to know about the container itself. An implementation of one concrete implementor of ITranslator could therefore be:
public class FileTranslator : ITranslator
{
// private fields
public FileTranslator( ISectionATranslator sectionAtrans,
ISectionBTranslator sectionBtrans,
ISectionCTranslator sectionCtrans)
{
this.sectionAtrans = sectionAtrans;
// etc
}
// implementation
}
Note here that FileTranslator knows nothing about which concrete classes actually implement the interfaces it depends on, nor does it need any sort of factory. In fact, the container will do this for you. There are several ways containers work this stuff out, one example is explicit config, something like:
<!-- absolutely fictitious configuration file, but similar to many frameworks -->
<ContainerConfig>
<ObjectResolver interface="ITranslator">
<ConcreteType type="FileTranslator">
<ConstructorInjection>
<Argument ordinal="0" type="SectionATranslator" />
<Argument ordinal="1" type="SectionBTranslator" />
<Argument ordinal="2" type="SectionCTranslator" />
</ConstructorInjection>
</ConcreteType>
</ObjectResolver>
</ContainerConfig>
Many frameworks don't even need you to define the specific constructor arguments, you can just state that if you want a ISectionATranslator then return a SectionATranslator and it will automatically create these before calling the constructor.
Also note that some frameworks provide the option to define these type resolution rules in code, using fluent style APIs, and some allow you to define multiple potential ways of resolving a particular type, via some name (perhaps a "Production" implementation versus a "UnitTest" implementation).
Note that I have kept the above deliberately vague because I don't want to say which framework is best (and to be honest, I think it depends on your individual needs) - check elsewhere on StackOverflow for framework comparisons, and please try a few out (perhaps you can try some without telling your boss!). Hopefully, however, the above shows why an IoC container can make your code much cleaner by removing the need for layers upon layers of factory classes.
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.