WCF initialization using Bootstrapper for Unity and Automapper - wcf

I am using Unity Container and Automapper and I'm looking for a place to call my initialization and bootstrapping code in my WCF Service. My internet searches have recommended one of four approaches as discussed here
http://blogs.msdn.com/b/wenlong/archive/2006/01/11/511514.aspx
(e.g.
1. Global.asax,
2. App_Code\AppInitialize,
3. custom ServiceHost, and
4. ServiceHostBase.InitializeRuntime)
However, I was also wondering if anyone has used the "Bootstrapper" project
http://bootstrapper.codeplex.com/
with the Unity and Automapper extensions.
So where/how is the best place to call the "Bootstrapper.Run()" code in a WCF Service? Sample code would be greatly appreciated. Thanks!

You can use web activator and call initialize method on your bootstrapper class. see details on https://www.nuget.org/packages/WebActivatorEx/

Related

Initialize mmvcross IOC for Windows Runtime Component Background Task

In building my current (first) Windows Phone app it requires me to create a Windows Runtime Component to achieve the functionality I require. In order for this setup to work and not duplicate a lot of code from my PCLs into the task class itself, I wanted to use the MMVMCross IOC that I am already using throughout the application.
Unfortunately, the Background Task (IBackgroundTask) is executed in an entirely different process. Trying to utilize the IOC via Mvx.Resolve throws a NullReferenceException. I cannot figure out how to initialize the IOC as the standard "setup.cs" method does not work in the Runtime Component.
I do not need the entire MVVMCross stack for this -- just the IOC.
Thank you.
I finally figured it out. I have to re-register on the background task, but to initialize you would call the basic initialize method on the simple IOC container:
Cirrious.CrossCore.IoC.MvxSimpleIoCContainer.Initialize();
Plugins were a problem, as the standard plugin mechanism is not available, but you can manually register the interfaces such as this:
Mvx.LazyConstructAndRegisterSingleton<IMvxFileStore>(() => new MvxWindowsCommonBlockingFileStore());
Of course, you can still register your other types and interfaces as you normally would.

How to wire up WCF Service Application, Unity and AutoMapper

I have been playing around the last couple of days with different solutions for mapping DTO's to entities for a VS2013, EF6, WCF Service App project.
It is a fairly large project that is currently undergoing a major refactoring to bring the legacy code under test (as well as port the ORM from OpenAccess to EF6).
To be honest I had never used AutoMapper before but what I saw I really liked so I set out to test it out in a demo app and to be honest I am a bit ashamed that I have been unable to achieve a working solution after hours of tinkering and Googling. Here is a breakdown of the project:
WCF Service Application template based project (.svc file w/code behind).
Using Unity 3.x for my IoC container and thus creating my own ServiceHostFactory inheriting from UnityServiceHostFactory.
Using current AutoMapper nuget package.
DTO's and DAL are in two separate libraries as expected, both of which are referenced by the service app project.
My goal is simple (I think): Wire up and create all of my maps in my composition root and inject the necessary objects (using my DI container) into the class that has domain knowledge of the DTO's and a reference to my DAL library. Anyone that needs a transformation would therefore only need to reference the transformation library.
The problem: Well, there are a couple of them...
1) I cannot find a working example of AutoMapper in Unity anywhere. The code snippet that is referenced many times across the web for registering AutoMapper in Unity (see below) references a Configuration class that doesn't seem to exist anymore and I cannot find any documentation on its deprecation:
container.RegisterType<AutoMapper.Configuration, AutoMapper.Configuration>(new PerThreadLifetimeManager(), new InjectionConstructor(typeof(ITypeMapFactory),
AutoMapper.Mappers.MapperRegistry.AllMappers())).RegisterType<ITypeMapFactory,
TypeMapFactoy>().RegisterType<IConfiguration, AutoMapper.Configuration>().RegisterType<IConfigurationProvider,
AutoMapper.Configuration>().RegisterType<IMappingEngine, MappingEngine>();
2) Where to create the maps themselves... I would assuming that I could perform this operation right in my ServiceHostFactory but is that the correct place? There is a Bootstrapper project out there but I have not gone down that road (yet) and would like to avoid it if possible.
3) Other than the obviously necessary reference to AutoMapper in the DTO lib, what would I be injecting into the instantition, the configuration object (assuming IConfiguration or IConfigurationProvider) and which class I am injecting into the constructor of the WCF service to gain access to the necessary object.
I know #3 is a little vague but since I cannot get AutoMapper bound in my Unity container, I cannot test/trial/error to figure out the other issues.
Any pointers would be greatly appreciated.
UPDATE
So I now have a working solution that is testing correctly but would still like to get confirmation that I am following any established best practices.
First off, the Unity container registration for AutoMapper (as of 11/13/2013) v3.x looks like this:
container
.RegisterType<ConfigurationStore, ConfigurationStore>
(
new ContainerControlledLifetimeManager()
, new InjectionConstructor(typeof(ITypeMapFactory)
, MapperRegistry.AllMappers())
)
.RegisterType<IConfigurationProvider, ConfigurationStore>()
.RegisterType<IConfiguration, ConfigurationStore>()
.RegisterType<IMappingEngine, MappingEngine>()
.RegisterType<ITypeMapFactory, TypeMapFactory>();
Right after all of my container registrations, I created and am calling a RegisterMaps() method inside of ConfigureContainer(). I created a test mapping that does both an auto mapping for like named properties as well as a custom mapping. I did this in my demo app for two reasons primarily:
I don't yet know AutoMapper in a WCF app hosted in IIS and injected with Unity well enough to fully understand its behavior. I do not seem to have to inject any kind of configuration object into my library that does the transformations and I am still reading through the source to understand its implementation.
As I understand it, there is a caching mechanism at play here and that if a mapping is not found in cache that it will create it on the fly. While this is great in theory, the only way I could then test my mappings that were occurring in my composition root was to do some sort of custom mapping and then call Mapper.Map in the library that performs mapping and returns the DTO.
All of that blathering aside, here is what I was able to accomplish.
WCF Service App (composition root) injects all of the necessary objects including my DtoConversionMapper instance.
The project is made up of the WCF Service App (comp root), DtoLib, DalLib, ContractsLib (interfaces).
In my ServiceFactoryHost I am able to create mappings, including custom mappings (i.e. map unlike named properties between my DTO and EF 6 entity).
The DtoConversionMapper class lives in the DtoLib library and looks like this: IExampleDto GetExampleDto(ExampleEntity entity);
Any library with a reference to the DtoLib can convert back and forth, including the Service App where the vast majority of these calls will take place.
Any guiding advice would be greatly appreciated but I do have a working demo now that I can test things out with while I work through this large refactoring.
Final Update
I changed the demo project just a little by adding another library (MappingLib) and moved all of my DTO conversions and mappings to it in a static method. While I still call the static method in my composition root after the Unity container is initialized, this gives me the added flexibility of being able to call that same map creation method in my NUnit unit test libraries, effectively eliminating any duplication of code surrounding auto mapper and makes it very testable.

Profiler lib for wcf + postsharp

We need to add a new profiling feature to our WCF application, for logging where time is spendt in the application. I'm looking at PostSharp for a convention driven approach of applying the logging and need some input on how to actually log it. I've already created a custom class for logging purposes, using StopWatch and can log the steps through the layers of my WCF application. However I'm wondering if there's a thread safe alternative library I could use in conjunction with PostSharp for this purpose. I've come across MiniProfiler, but it seems to be intended for ASP.NET MVC applications mainly. Any other frameworks I should consider or should I just use my custom class?
Thanks
I did something like that in the past using a IClientMessageInspector implemented on a custom IEndpointBehavior.
Depending on what kind of logging you want, this might just do the trick. There's an example in the following link
IClientMessageInspector Interface
PostSharp itself is thread-safe. The aspects that you write may be thread-unsafe if poorly written, but there's always a way to make them thread-safe.
If you're using OnMethodBoundaryAspect and need to pass something from OnEntry to OnSuccess, store the initial stopwatch value in OnMethodExecutionArgs.MethodExecutionTag.

how to make WCF service use a specific DataContractSerializer constructor overload?

DataContractSerializer has many constructor overloads, and I'd like to be able to specify how my WCF service should initialize the DataContractSerializer it uses. How would you go about doing this? Is it easier to configure this in the .config file or in C#?
A WCF service always appears to use this one by default.
If possible, please give an example of how to specify DataContractSerializer using this constructor for KnownTypes.
This MSDN forum post shows how to swap the serializer in WCF with another. You could create your own wrapper with the constructor that you want and swap it in.
I figured out how to do this. See
http://blogs.msdn.com/b/youssefm/archive/2009/06/05/introducing-a-new-datacontractserializer-feature-the-datacontractresolver.aspx
and
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer(v=vs.85).aspx
for guidance. Hope this helps.

Castle Monorail and Ninject 2 integration

I want to use Ninject 2 on Castle Monorail. Searching on google, I found nothing about this.
I know there is Windsor which magically can integrate with Monorail, same as Ninject (with MVC extension) with ASP.NET MVC.
What steps I need to do to integrate DI framework (other than Windsor) with Monorail ? (any website link, tutorial, or code sample (preferably using Ninject 2))
fyi, I'm using C#
I don't think there's any documentation about this, but it's quite simple really. There's no magic to it. Since MonoRail and Windsor are completely separate projects, all you have to do is see how they integrate, then do the same for Ninject instead of Windsor.
More concretely, start with the MonoRailFacility which is the root of the integration. Instead of a Windsor facility, you'd use a Ninject module. Note it registers some components: IControllerTree, IWizardPageFactory, etc. The most important is IControllerFactory, which lets you resolve controllers from the container (in your case Ninject). You can leave all others as default for now (e.g. IFilterFactory/DefaultFilterFactory), and implement them as needed (i.e. when you need container control of filters).
Then call ServiceProviderLocator.Instance.AddLocatorStrategy(new NinjectAccessorStrategy()); where NinjectAccessorStrategy is an implementation of IAccessorStrategy which returns the Ninject kernel as a Castle.Core.IServiceProviderEx (which is nothing but a trivial extension of System.IServiceProvider). Since the Ninject kernel already implements IServiceProvider, it's trivial to write an adapter for IServiceProviderEx.