Windsor Typed Factory facility, passing arguments when using singleton lifestyle - singleton

I am using Castle Windsor.
I have two component types where the implementation can be selected at runtime on a GUI. To handle this, I am resolving them by name. To handle resolving them by name, I am using the Typed Factory Facility.
One of the component types depends on the other. To handle the dependency, I am passing the argument as a factory method/constructor parameter argument.
Here is a redacted and abridged version of this factory interface:
public interface IModelFactory
{
IMyDomainCommandFactory GetFooCommandFactory();
IMyDomainCommandFactory GetBarCommandFactory();
IMyDomainStrategy GetCreateSpecificSizeStrategy(int size, IMyDomainCommandFactory commandFactory);
IMyDomainStrategy GetCreateUntilFailureStrategy(IMyDomainCommandFactory commandFactory);
}
Note that I am using my own implementations for IMyDomainCommandFactory, rather than using the Typed Factory facility. Those factories have intentionally complex behavior, and the facility doesn't suit their needs.
The problem I am noticing is that if I register my strategy components with a singleton lifestyle, I always get back the same instance, even if I pass different arguments to the getter.
In my opinion, this goes against the Principal of Least Astonishment, but maybe other people have a different opinion :) Should this be considered a bug?
If not, is there a clean way to get the container or factory to create only one instance per argument combination?

Depending how you look at it, but certainly instance per combination of parameters can't be called a singleton so I say it would go against PoLA if Windsor did implement the behavior you'd expect.
If you want it, you need a custom, non-singleton lifestyle.

Related

Jackon JSON: Polymorphic deseralization when subclasses are unknown

I'm trying to do some polymorphic deseralization of JSON using Jackson, however the list of subclasses is unknown at compile time, so I can't use a #JsonSubtype annotation on the base class.
Instead I want to use a TypeIdResolver class to perform the conversion to and from a property value.
The list of possible subclasses I might encounter will be dynamic, but they are all registered at run time with a registry. So I would appear to need my TypeIdResolver object to have a reference to that registry class. It has to operate in what is essentially a dependency injection environment (i.e I can't have a singleton class that the TypeIdResolver consults), so I think I need to inject the registry class into the TypeIdResolver. The kind of code I think I want write is:
ObjectMapper mapper = new ObjectMapper();
mapper.something(new MyTypeIdResolver(subclassRegistry));
mapper.readValue(...)
However, I can't find a way of doing the bit in the middle. The only methods I can find use java annotations to specify what the TypeIdResolver is going to be.
This question Is there a way to specify #JsonTypeIdResolver on mapper config instead of annotation? is the same, though the motivation is different, and the answer is to use an annotation mixin, which won't work here.
SimpleModule has method registerSubtypes(), with which you can register subtypes. If only passing Classes, simple class name is used as type id, but you can also pass NamedType to define type id to use for sub-class.
So, if you do know full set, just build SimpleModule, register that to mapper.
Otherwise if this does not work you may need to resort to just sharing data via static singleton instance (if applicable), or even ThreadLocal.
Note that in the end what I did was abandon Jackson and write my own much simpler framework based on javax.json that just did the kinds of serialisation I wanted in a much more straightforward fashion. I was only dealing with simple DTO (data transfer object) classes, so it was just much simpler to write my own simple framework.

Dependency injection - somewhere between constructor and container

I have a situation where i am currently using constructor dependency injection for a small module that fits inside a larger web framework.
Its working fine but now there is a new class being introduced that requires 2 objects passed to it. But, 1 of the objects requires a lot of work to get set up - essentially it invovles around 4 method calls which create other objects in order to get it into a working state ready to be passed to my object.
My dilemna is that constructor injection is no use due to the work involved, but introducing a ioc container is way overboard, especially for this 1 off use case.
So, how should this be handled? Is there some sort of solution that sits in the middle of these two options?
You've effectively got four five choices:
Poor Man's DI (create objects manually and pass to constructors)
IoC container
Factory method
Abstract factory
Builder (thanks, Mark Seemann!)
I usually start off with an IoC container, but I do a lot of DI. (I've seen too many tightly-coupled codebases.)
If you don't want to introduce an IoC container, I'd lean towards Poor Man's DI.
If you're working in any object-oriented language (not just C#), I recommend reading the book Dependency Injection in .NET. It covers the patterns and anti-patterns in detail.
1 of the objects requires a lot of work to get set up - essentially it invovles around 4 method calls which create other objects in order to get it into a working state ready to be passed to my object.
OK, then create the object and pass the completely initialized object to the constructor, in which it needs to go.
Creating that object sounds like a job for a Builder or Factory.
My dilemna is that constructor injection is no use due to the work
involved,
I prefer Constructor Injection and see no reasons to avoid it.
Using modern IoC frameworks you can specify creation logic that involves "a lot of work to get set up" via factory/ factory method.
No matter how many steps are needed to build an instance of IMyService, you can simply use a constructor dependency to inject it.
Castle Windsor
container.AddFacility<FactorySupportFacility>()
.Register(
Component.For<IMyFactory>().ImplementedBy<MyFactory>(),
Component.For<IMyService>()
.UsingFactoryMethod(k => k.Resolve<IMyFactory>().Create())
);
Unity
var container = new UnityContainer();
container.RegisterType<IMyFactory, MyFactory>();
container.RegisterType<IMyService>(
new InjectionFactory(c => c.Resolve<IMyFactory>().Create()));

WCF data contract design with dependency injection

So I have a layered application that I am adding a WCF service interface on top of. The service is simply a facade with all of our business logic already existing in Business Objects (BOs) within the Business Logic Layer (BLL) which is a class library. Within the BLL we use constructor injection to inject dependencies into the BOs. This is all working with good unit testing, etc. On to the problem...
Ordinarily I'd simply create a set of Request/Response objects as DataContracts for each service method with the appropriate properties for the operation. If the operation required one of our "entities" to be passed either to or from the method, I'd simply define a property of that type and everything would be fine (all of our BOs are serializable). However when one of these "entities" is passed into a service method, WCF deserializes the object without ever invoking the constructors we've defined and, as a result, the dependencies don't resolve.
Let's use the case of a service method called CreateSomething. I'd normally define this as a service operation with a signature like:
CreateSomethingResponse CreateSomething(CreateSomethingRequest request);
CreateSomethingRequest would be a DataContract and have amongst its properties a property of type Something that represented the "entity" being passed into the service. Something, in this case, is a business object that expects to receive an instance of the ISomethingRepository interface from the DI container when instantiated - which, as I said above, does not happen when WCF deserializes the object on the server.
Option #2 is to remove the Something property from the DataContract and define each of the properties explicitly in my DataContract then inside my service method, create a new instance of the Something class, letting the container inject the dependency, then map the property values from the DataContract object into the BO. And I can certainly do that but I am concerned about now having two places to make changes if, say, I want to add a property to the Something type. And, with a lot of properties, there's a lot of code duplication.
Has anyone crossed this bridge and, if so, can you share your thoughts and how you have or would approach this situation in your own applications? Thx!!!
There are two answers on your problem:
First: Do not send your entities and use data transfer objects instead. Your entities are business objects with its logic and data. The logic of business objects is most probably used to control the data. So let the business object control its data in business layer and exchange only dummy crates.
Second: If you don't want to follow the first approach, check documentation of your IoC container. There are ususally two methods for resolving dependencies. For example Unity offers:
Resolve - builds new instance and injects all dependencies (necessary for constructor injection)
BuildUp - takes existing instance and resolves all property dependencies. This should be your choice.
Thanks, Ladislav, for your answer as you confirmed what was already in my head.
What I ended up doing was to change my approach a little. I realized that my use of a business object, per se, was overkill and unnecessary. Or perhaps, just misdirected. When evaluating my requirements, I realized that I could "simplify" my approach and make everything work. By taking each logical layer in my application and looking at what data needed to pass between the layers, I found a design that works.
First, for my business logic layer, instead of a business object, I implemented a Unit of Work object: SomethingManager. SomethingManager is tied to my root Something entity so that any action I want to perform on or with Something is done through the SomethingManager. This includes methods like GetById, GetAll, Save and Delete.
The SomethingManager class accepts two objects in its constructor: an IValidator<Something> and an ISomethingRepository. These will be injected in by the IoC container. The former lets me perform all of the necessary validation using whatever framework we chose (initially the Validation Application Block) and the latter gives me persistance ignorance and abstracts the use of Linq-to-SQL today and makes upgrading to EF4 much easier later on.
For my service layer, I've wired the IoC container (Unity in this case) into WCF so the service instance is created by the container. This allows me to inject an instance of ISomethingManager into my service. Using the interface, I can break the dependency and easily unit test the service class. Plus, because the container is injecting the ISomethingManager instance, it is constructing it and will automatically resolve it's dependencies.
I then created DataContracts to represent how the data should appear when transferred across the wire via the service. Each Request/Response object contains these DataContracts as DataMembers rather than referencing my entity classes (or BOs) directly. It is up to the service method to map the data coming from or going to the Business Logic Layer (via ISomethingManager) - using AutoMapper to make this clean and efficient.
Back in the data layer, I've simply extended the generated entity classes by defining a partial class that implements the desired interface from the BLL. For instance, the Something L2S entity has a partial defined that implements ISomething. And ISomething is what the SomethingManager (and ISomethingManager interface) and ISomethingRepository work with making it very easy to query the database and pass the L2S entity up the chain for the service layer to consume and pass on (without the service layer having any knowledge or dependency on the L2S implementation).
I appreciate any comment, questions, criticisms or suggestions anyone has on this approach.

Does ChannelFactory implement a factory pattern?

I’ve started learning WCF and I’m already utterly confused. I did a bit of reading on factory pattern and I can’t figure out how or why does ChannelFactory<> implement it.
Namely, the whole idea of a factory pattern is that factory abstracts the creation and initialization of the product from the client and thus if new type of product is introduced, client code doesn’t need to change and thus can immediately start using the new product.
ChannelFactory<IRequestChannel> factory = new
ChannelFactory<IRequestChannel>(binding, address);
IRequestChannel channel = factory.CreateChannel();
The following is not a valid code, but it’s just used to demonstrate that, as far as I can tell, ChannelFactory doesn’t bring any benefits over directly instantiating specific channel class:
IRequestChannel channel=new RequestChannelClass(binding, address);
a) Only benefit of the first example ( implementing the factory pattern ) is that client code doesn’t need to change in the event that the type of object returned by factory.CreateChannel is changed sometime in the future.
But if that’s the reason for implementing factory pattern, then any method returning an object should implement a factory pattern, just in case the type of returned object ever changes in the future?!
c) Thus, if ChannelFactory<>.CreateChannel really implemented factory pattern, then client code would be able to inform factory.GetFactory (say via parameter) of what type should an object/product returned by factory.CreateFactory be?!
d) Similarly, as far as I can tell, ChannelFactory class also doesn't implement a factory pattern?
thank you
REPLYING TO Justin Niessner:
b) The Factory pattern doesn't
necessarily require you to be able to
specify the concrete type to be
created. It also allows for the
factory to determine the concrete type
based on the parameters passed to it
(in this case, binding and address).
So ChannelFactory.CreateChannel choose a concrete type to return based on binding and address values? I thought it always returns the same concrete type, regardless of address and binding values?!
As I’ve asked the other two posters, would you agree that if ChannelFactory.CreateChannel always returned an instance of the same concrete type, regardless of the binding and address values, then ChannelFactory wouldn’t have a factory pattern implemented?
REPLYING TO Kevin Nelson
A) There are 2 benefits. 1)
implementing code doesn't have to
change if you start using a new
implementation of IRequestChannel.
True, but as I’ve mentioned to other posters, if that’s the only requirement for class to be qualified as a class implementing a factory pattern , then any class with a method ( with an interface type as return type ) that creates and returns a concrete instance, implements a factory pattern? As far as I can tell, factory pattern is when factory produces different products based on values somehow supplied by a client code?!
On the other hand, if I correctly understood Steve Ellinger, then based on binding and address values ( passed to constructor of ChannelFactory), the call to ChannelFactory.CreateChannel will choose the concrete type to return based on binding and address values( supplied to constructor ). If that is the case, then I can understand why we say ChannelFactory implements factory pattern?!
So would you agree that if ChannelFactory.CreateChannel always returned an instance of the same concrete type, regardless of the binding and address values, then ChannelFactory wouldn’t have a factory pattern implemented?
REPLYING TO Steve Ellinger
IRequestChannel is implemented by the
abstract class RequestChannel. In .Net
4.0 HttpChannelFactory.HttpRequestChannel,
ReliableRequestSessionChannel and
StreamedFramingRequestChannel all
inherit from RequestChannel. So:
a) You say the only benefit, but
actually I think this is a significant
benefit. Keep in mind, this also makes
WCF extensible and more flexible.
But then we could claim that any class with a method ( with an interface type as return type ) that creates and returns a concrete instance implements a factory pattern?
c) The client code does tell the
factory which to return, indirectly by
the passed binding and address.
I thought ChannelFactory.CreateChannel will always return in instance of the same concrete type, regardless of the binding and address passed to constructor of ChannelFactory.But you’re saying that based on binding and address values ( passed to constructor of ChannelFactory), the call to ChannelFactory.CreateChannel will return one of the following types: HttpChannelFactory.HttpRequestChannel ,ReliableRequestSessionChannel and StreamedFramingRequestChannel?
If that is the case, then I can understand why we say ChannelFactory implements factory pattern?!
So would you agree that if ChannelFactory.CreateChannel always returned an instance of the same concrete type, regardless of the binding and address values, then ChannelFactory wouldn’t have a factory pattern implemented?
SECOND REPLY TO Steve Ellinger
a) So depending on the binding and address values, ChannelFactory.CreateChannel returns either HttpRequestChannel ,ReliableRequestSessionChannel or StreamedFramingRequestChannel? Or may it also return some other types also?
b) if client code will always use channel instance of the same type (say HttpRequestChannel ), then there's nothing wrong if instead of using ChannelFactory.CreateChannel we directly instantiate HttpRequestChannel instance:
HttpRequestChannel channel = new HttpRequestChannel( ... )
c) BTW - any idea why msdn doesn't contain any entries describing HttpRequestChannel ,ReliableRequestSessionChannel and `StreamedFramingRequestChannel' classes?
IRequestChannel is implemented by the abstract class RequestChannel. In .Net 4.0 HttpChannelFactory.HttpRequestChannel, ReliableRequestSessionChannel and StreamedFramingRequestChannel all inherit from RequestChannel. So:
a) You say the only benefit, but actually I think this is a significant benefit. Keep in mind, this also makes WCF extensible and more flexible.
c) The client code does tell the factory which to return, indirectly by the passed binding and address. I for one would not want to go through all my code to change a concrete type because Microsoft decided to obsolete the one I was using.
d) Yes, given the structure mentioned at the start, this is a typical Factory pattern implementation.
Edit:
a factory pattern?
But then we could claim that any class
with a method ( with an interface type
as return type ) that creates and
returns a concrete instance implements
a factory pattern?
Not necessarily, to quote the Design Patterns book: the abstract factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.
So would you agree that if
ChannelFactory.CreateChannel always
returned an instance of the same
concrete type, regardless of the
binding and address values, then
ChannelFactory wouldn’t have a factory
pattern implemented?
Yes
Edit2:
a) It can return other types because it is possible to create custom bindings in WCF
b) & c) HttpChannelFactory.HttpRequestChannel is a protected class, ReliableRequestSessionChannel and StreamedFramingRequestChannel are internal classes; this is why you can't find them on msdn, and also why you can't instantiate these classes directly. I found out about them via Reflector, my point in mentioning them is that ChannelFactory does not necessarily return the same concrete type all the time
The Factory pattern is used to return a Concrete Implementation of a more generic class/interface.
In this case, ChannelFactory is returning a concrete implementation of IRequestChannel. Nowhere in any of your code are you telling the factory which concrete class to return which is what makes this a Factory. As for your points:
a) It is often considered good coding practice to return the least specific type possible. If you can get away with returning an instance of an interface, do it. It will reduce maintenance headaches in the future.
Keep in mind though that returning the least specific type has nothing to do with the Factory pattern. The Factory pattern is specific to the creation of an instance of an object.
b) The Factory pattern doesn't necessarily require you to be able to specify the concrete type to be created. It also allows for the factory to determine the concrete type based on the parameters passed to it (in this case, binding and address).
c) Yes, the ChannelFactory does implement the Factory pattern.
There are others that are probably more efficient with patterns (and explaining them) than I am, but here goes:
A) There are 2 benefits. 1) implementing code doesn't have to change if you start using a new implementation of IRequestChannel. 2) This also enables you to make Mock objects. In your unit test project, you tell your ChannelFactory to instantiate a Mock IRequestChannel. This way, you can focus your unit test onto just the specifics of the method you are testing rather than having to create a behemoth test that instantiates real instances of everything, etc. (If you're unfamiliar, look up Test Driven Development (TDD), Inversion of Control (IoC), and Dependency Injection (basically a subset of IoC).
B) I would say that you generally want to use the factory pattern between layers, not within layers. E.g. your service layer would implement a factory for your repository layer classes. This way, if your ICustomerRepostory changes from an NHibernateCustomerRepository to a CouchDBCustomerRespository...your service layer doesn't have to know anything about this change.
Other poster answered the other issues, I think...so I'll leave C & D alone.
REPLY EDIT:
So would you agree that if
ChannelFactory.CreateChannel always
returned an instance of the same
concrete type, regardless of the
binding and address values, then
ChannelFactory wouldn’t have a factory
pattern implemented?
Sorry, probably over my head as to the semantics of it...but to my understanding, the point isn't so much whether it does return more than one concrete class, but in its ability to return a different concrete class if the need arises. If it's not able to produce different concrete classes, then it wouldn't be a factory...but if it "can" produce different concrete classes if and when the need arises, then it is a factory pattern. Beyond that, I'll have to declare ignorance...and even in that, I'm not saying I can't be wrong.

Representing parameters/configurations/settings

Alright, so let's say I'm writing an application using an object-oriented language, and I have a set of key-value pairs that represent program parameters/configuration/options/settings/etc. These may be initial values of certain variables, or just values that aren't bound to change except between sessions. How should I represent these values in my data model?
My initial thought is to simply store all the values in single class that is globally accessible (singleton perhaps), because these values will be used in various places in the code. This, however, will make all the other classes dependent on this singleton.
Is that a problem in this situation? Is there another, ideal solution that I haven't thought of? How do you people usually represent this type of data? Is there anything else I should be aware of concerning this problem?
Thanks
You might want to use dependency injection. Create an interface IConfigurationProvider. Create a class DefaultConfigurationProvider that implements that interface and does the actual task. Makes other object that rely on config data expect an IConfigurationProvider instance and provide them with an instance of DefaultConfigurationProvider. Most dependency injection frameworks will handle this for you.
"Is that a problem [with a Singleton configuration]?
Not really.
"all the other classes dependent on this singleton"
Not really. You can easily design things so that some classes get configuration, and provide it to other classes.
This is a question of resposnsibility -- what class/package/method has responsibility for this configuration issue. And the answer should be very, very few classes need to know the configuration.
Your model, for example, should probably be focused on the problem domain independent of implementation nuance. It may not need any configuration.
"Is there another, ideal solution that I haven't thought of?"
Not really. The configuration problem is hard. You may have a default configuration, overrides to the default configuration, command-line options. It's quite complex.
"How do you people usually represent this type of data?"
A Singleton for the most part. Generally, a few key "top-level" classes in a given application must know the configuration and use that information to configure all of the other classes.
For a command-line program, the class that is invoked by the "main" program to parse arguments will also know about the configuration. And that's it.
For a web app, a top-level piece of the web app uses the configuration to build, configure, customize or instantiate other things. In many cases, a key Factory will use the configuration to decide what to create. A key Builder may require configuration to customize composite objects its building.
Configuration is not "global". It is not seen by all classes. It is -- like the database -- a precious resource and it is carefully wrapped by classes that have responsibility for handling configuration.
"Is there anything else I should be aware of concerning this problem?"
Yes. The configuration Singleton is not global. It is a scarce, precious resource that is used in a few key places. The fewer the better.
It depends on your concrete situation.
For example, you can provide class Context with method getParameter (String name) and
setParameter (String name, Object value) and many other methods which you need to preserve config parameters.
You can transfer Context as a parameter in constructor of class which should use config. parameters:
public class ConfigUser {
private Context c;
public ConfigUser (Context c) {
this.c = c;
}
...
}