AutoMapper classes with a Transient lifestyle in IoC - castle-windsor

I'm using AutoMapper to map domain entities to view models in an Asp.Net MVC app. I register these mapping classes in Castle Windsor so they are available to the controller thru ctor dependency injection. These mapping classes has a virtual CreateMap method where I can override AutoMapper's mapping, telling it how to map fields from the entity to the view model, which fields to ignore, pointing to methods that transforms the data, etc. All of this is working well; big kudos to the people behind AutoMapper!
So far I've been registering the mapping classes with a Singleton lifestyle in Windsor, but one of them needs to use the IAuthorizationRepository from Rhino.Security which needs to have its components registered as Transient. This forces me to register the mapping classes also as transient, because a singleton mapping class holding a reference to a transient IAuthorizationRepository causes problems the second time the mapper is used (i.e., ISession is already closed errors).
Is it a waste of resources to register all of these mapping classes with a Transient lifestyle, which will cause the mapping class to be instantiated and the CreateMap method to run each time the system wants to map a domain entity to a view model?
Or should I try to find a way to separate the IAuthorizationRepository from the mapping class so I can keep the mapping classes as Singletons?
Thanks
Dan

Another way around it is using the TypedFactoryFacility, then instead of injecting IAuthorizationRepository into your singletons you can inject Func<IAuthorizationRepository>

Related

WPF+REST+EF: what is the best way to organize DTO's?

I have a WPF MVVM app with 3 layers:
UI
Services
DAL
and some item, for example Order. I need 3 DTO:
Class for MVVM layer, with PropertyChanged notification;
Class for Json deserializer (get objects by REST API)
Class for Entity Framework (cache data in DB).
Well, I can use ONE class for all three cases, but this will be mix of different attributes (from EF, JSon, MVVM) and excess dependencies of layers.
Another way: make 3 classes, each layer has own class, and use AutoMapper for fast convert between. No bad, but 3 almost identical (90%) copy of each DTO class... not elegant solution.
What is the best approach? What do you use?
Thanks.
What is the best approach? What do you use?
The second approach, i.e. you define your business objects in a separate assembly that you can reference from all your applications. These classes should not implement any client-specific interfaces such as INotifyPropertyChanged but be pure POCO classes that contains business logic only.
In your WPF application, you then create a view model class that implements the INotifyPropertyChanged interface and wraps any properties of the business object that it makes sense to expose to and bind to from the view.
The view model then has a reference to the model and the view binds to the view model. This is typically how the MVVM design pattern is (or should be) implemented in a WPF application. The view model class contains your application logic, for example how to notify the view when a data bound property value is changed, and the model contains the business logic that is the same across all platforms and applications.
Of course this means that you will end up with a larger number of classes in total but this is not necessarily a bad thing as each class has its own responsibility.
The responsibility of a view model is to act as a model for the application specific XAML view whereas the responsibility of the model class is to implement the business logic and the responsibility of the DTO class is to simply transfer the data between the different tiers. This is a far better solution - at least in my opinion and probably in most enterprise architect's opinions as well - than defining a single class that implements all kind of UI specific logic just for the sake of reducing the number of classes.

In WinRT, what is the visibility of the default .Ctor?

As an example (and the reason of my question), the class Windows.XAML.Media.Transform, as far as I can see from the WinMD info shown by ILDASM, has no defined constructor.
But if I try to derive from that class, on my C# project, compiler complains that non constructor can be found.
This seems to me that this could be a result of hidden visibility of the constructor.
A same effect can be achieved in C# declaring a private (or internal) Constructor, but it must be declared, otherwise a public constructor is created by the compiler, and the class is indeed derivable.
Any hint?
I think what's going on here is, that the class has explicitly declared an internal (default) constructor, no public constructor(s), so the developers can inherit from the class within the defining assembly. Everybody else, outside the assembly is prevented from beeing able to inherit from the class.
WinRT is an evolution of the COM concepts and is a quite different story as we are talking about binary components and not source inheritance.
The most important thing in this ABI story is that the only things of the component that can be used are the ones exposed via interfaces.
Constructors cannot be defined in interfaces nor can statics, and this means that WinRT need interfaces for these too.
C# viewes of WinRT components are an artifact of the language projection and not the real layout of the component.
To fully understand what's there, you should look at the component in C++, using the native library WRL that is the library used to build the WinRT APIs.
The Constructor is a projection for the factory interface of the WinRT component (and statics, new to WinRT as they didn't exist in COM, have a similar treatment).
When you "new" from C# an object, a Factory component associated to the component is first created. After this the factory create the object.
For this reason the constructor question should be seen in terms of factory component and not in terms of constructor (that exist in the underlying implementation but it doesn't really matter as what you see of the component is only its binary contract, the ABI).
So there are different options:
1. A factory does not exist and you cannot create the component. If the Factory interface is internal you can't use it and can't create the object.
2. A factory exists and expose the default constructor. In C# you can new the object
3. A custom factory exists and expose custom constructors (whit parameters).
ITransformFactory is private and I believe this explain the behavior you have seen.
There is much more on this topic as WinRT aggregation is the way they provide binary inheritance and versioning, but this is another (very long) story.
Still digging, and never will stop, that's the fun part of our job :)

Is is possible to add additional registrations to an existing WindsorContainer using XmlInterpreter?

I'd like to be able to register some types on a container and then top these up with some additional type declared in an XML configuration file. Unfortunately, IConfigurationInterpreter (implemented by XmlInterpreter) is only available in the WindsorContainer() constructor, not in any AddXXX() methods. Is there any other way I can achieve this without resorting to parent/child containers (that may soon be unsupported).
Background: Our large application is only starting to use the Castle framework to register and resolve some of it's components. Because Castle is being retrofitted into this app we're using a singleton class to maintain a global instance of WindsorContainer(). In unit tests, we need to wire up this container instance to use a combination of custom mock implementations (specific to the test) + some default mock implementations. For DLL dependency reasons, these mock class types are unavailable in this unit test fixture abstract base class so dynamic registration (using strings) is necessary. I was hoping to use an XML resource file to register the default mocks. Otherwise I have to do the same using an IWindsorInstaller implementation that's really duplicating what XmlInterpreter does. This API appears to be forcing this direction.
I think these will work ...
container.Install(Castle.Windsor.Installer.Configuration.FromXml(resource))
OR
container.Install(Castle.Windsor.Installer.Configuration.FromXmlFile(path))
which both avoid use of the IConfigurationInterpreter interface.

Castle Windsor - should I reference the container from other classes?

I'm about to embark on a new project using Windsor, but I've been wondering about running into scenarios where a Class A might need to instantiate Class B, but it's not feasible or possible for Windsor to inject an instance of Class B into it. I'm struggling to think of a scenario, but here goes:
Say I have a business entity "Customer" that gets passed to a WCF service. This class has an Ent.Lib self-validation method, which in turn uses a helper class "CustomerValidator". The Customer object received by the service has been deserialized by WCF, so Windsor plays no part in its instantiation, so I can't inject any dependencies. Nor can I pass my CustomerValidator to the self-validation method as it must follow a particular signature for Ent.Lib. So how could I instantiate the CustomerValidator within this class/method? I still want to utilise Windsor rather than simply doing a "var cv = new CustomerValidator();".
It's not a great example as it could be solved in different ways, e.g. passing the Customer object to a validation method rather than having the validation method in the Customer class, but it offers a possible scenario for discussion.
I could expose my WindsorContainer as a public singleton, accessible by any code that needs it, but that seems to be frowned upon. Any other suggestions?
should I reference the container from other classes?
No. By referencing the container, you add complicated and unnecessary dependency to your class which will complicate testing and increase complexity.
The Customer object received by the service has been deserialized by WCF, so Windsor plays no part in its instantiation, so I can't inject any dependencies.
I think this is the direction you should go, try to explore if there really isn't any way to take control of deserialization so you can inject dependencies.
If that fails, consider using http://commonservicelocator.codeplex.com/. Its Microsoft's service location implementation with Windsor adapter available. It's basically the same pattern as if you referenced the container but you don't introduce dependency on specific container implementation. Also I think it will be easier to mock for testing.

Unit testing with a Singleton

I am developing an AS3 application which uses a Singleton class to store Metrics in Arrays. It's a Singleton because I only ever want one instance of this class to be created and it needs to be created from any part of the app.
The difficulty comes when I want to unit test this class. I thought adding public getters and setters would enable me to unit test this properly and would be useful for my app. I have read that changing to a Factory pattern will enable unit testing or using Inversion of control. This would of course make it more flexible too. I would like to know of people's thoughts on this matter as there are SO many conflicting opinions on this!
Thanks
Chris
If you're using an IoC framework, then make your consumers require an instance of the service in their constructor, and configure the IoC framework to only build one instance and keep handing it out to all requests in the entire application. This is the default behavior of Castle Windsor in my experience.
For unit testing you can use a Mock object in place of the real object.