At what point does activation of services happen in Ninject when requesting IEnumerable - ninject

We are using Ninject in work as part of a modification to our legacy system. In some parts of the application we have opted to use a static Service Locator that wraps around Ninject. This is really only a static adapter.
When I request IEnumerable<IFoo> via our Service Locator it simply requests the same via Ninject's GetAll method. What I wanted to know is since I haven't actually enumerated the list, will all services remain inactive.
The reason I am asking is we are using Ninject to replace an old controller locator in a WinForms app. Some of these controllers are hairy so I don't want them activating until I have filtered to the one I want. How we are doing this is applying a Where clause to the collection on the service locator and then using FirstOrDefault to pick the correct one.
My understanding is that the activation will happen on enumeration (in our case at FirstOrDefault) is this correct?

You are correct that the GetAll doesn't actually do anything until you enumerate it in some manner. When you ask for an IEnumerable, each item pulled brings it to life - even if it's about to be filtered by a Where (the only way it could is if IQueryable were involved).
Each item Activated, will be Deactivated in line with the normal scoping rules.
The best way to avoid this is by having a .When... or other condition dictating the filtering.
DO NOT READ PAST THIS POINT - BAD ADVICE FOLLOWS.
A mad Hack is to request an IEnumerable<Lazy<T>> (which will require Ninject.Extensions.Factory). Good related article.

Related

Implementing .Net DI Compile Time Proxies?

I'm not so much seeking a specific implementation but trying to figure out the proper terms for what I'm trying to do so I can properly research the topic.
I have a bunch of interfaces and those interfaces are implemented by controllers, repositories, services and whatnot. Somewhere in the start up process of the application we're using the Castle.MicroKernel.Registration.Component class to register the classes to use for a particular interface. For instance:
Component.For<IPaginationService>().ImplementedBy<PaginationService>().LifeStyle.Transient
Recently I became interested in creating an audit trail of every class and method call. There's a few hundred of these classes so writing a proxy class for each one by hand isn't very practical. I could use a template to generate the code but I'd rather not blow up our code base with all that.
So I'm curious if there's some kind of on the fly solution. I know nHibernate creates proxy classes at some point which overlay all the entity classes. Can someone give me some guidance on how I might be able to do something similar here?
Something like:
Component.For<IPaginationService>().ImplementedBy<ProxyFor<PaginationService>>().LifeStyle.Transient
Obviously that won't work because I can only use generics to generalize the types of methods but not the methods themselves. Is there some tricky reflection approach I can use to do this?
You are looking for what Castle Windsor calls interceptors. It's an aspect-oriented way to tackle cross-cutting concerns -- auditing is certainly one of them. See documentation, or an article about the approach:
Aspect oriented programming is an approach that effectively “injects” pieces of code before or after an existing operation. This works by defining an Inteceptor wrapping the logic being invoked then registering it to run whenever a particular set/sub-set of methods are called.
If you want to apply it to many registered services, read more about interceptor selection mechanisms: IModelInterceptorsSelector helps there.
Using PostSharp, things like this can be even done at compile time. This can speed the resulting application, but when used correctly, interceptors are not slow.

NServiceBus Unobtrusive Conventions DefiningCommandsAs multiple times

It seems that I cannot define commands/events conventions more than once. Every registered convention will override previous.
This works:
configuration.Conventions()
.DefiningCommandsAs(
type => type.FullName == "MyProject1.CommandA" || type.FullName == "MyProject2.CommandB");
But this doesn't:
configuration.Conventions()
.DefiningCommandsAs(
type => type.FullName == "MyProject1.CommandA");
configuration.Conventions()
.DefiningCommandsAs(
type => type.FullName == "MyProject2.CommandB");
Why do I need this:
I'm developing a package that once referenced in NSB project will perform periodic actions (send messages). It needs to define own command conventions in INeedInitialization which will be picked up during assembly scanning. I don't want the user of the package to know that he needs to register conventions of the package. However the host project needs to register own conventions for commands. So it seems at the moment I either need to resort to Marker interfaces (which I don't want to do, there is a good reason why Unobtrusive mode was introduced) or come up with conventions like all commands must reside in *.Commands.* namespace which I don't like either.
So the questions is how to make package register it's own conventions unobtrusively and transparently to the Host.
Edit
Another way I can think of hacking around this is implementing a shared convention singleton and delegate registration of conventions to it. That singleton will then remember all conventions and will keep appending them every time. Not beautiful, but not uglier than other 2 options.
Message conventions not supporting multiple calls is definitely by design. This is to prevent having multiple opinions on what a message might be. Having them be additive implies that anybody can have an opinion.
So this pattern is meant to provide friction against just that, to get you to agree on one definition of what Command means inside the entire system. Basically, SOA Tenet #4: Service compatibility is based upon policy. A lot of times this is the "namespace ending in .Commands" pattern; I've used that one personally and it works well.
I do work for Particular, so while nothing is ever set in stone, I can be reasonably confident in saying there are no plans to change this in V6.
If you absolutely need to do something different, your idea in your Edit of creating some sort of MessageRegistry singleton and having the convention delegate to MessageRegistry.IsCommand(Type) is perfectly valid. In V5 nothing will be executed until the bus starts so as long as the MessageRegistry is filled before the bus starts (which could also be accomplished from within INeedInitialization) then everything should work great.
If you do go down that route I'd encourage you to go all the way and have your registry singleton responsible for other metadata like TimeToBeReceived, DataBus, WireEncryptedString, Express, and any other attribute-based message metadata as well.

Data binding without a ViewModel

I am doing something I have never tried before. I am trying to create dynamic UI and bind it to a dynamic model. In other words, my web service is going to send back a small metadata description of my UI and the raw data to bind to it. Therefore, at build time, I don't know what UI I will be constructing and I don't know what my model will be. Binding them together seems VERY difficult if not impossible.
Mvx allows me to bind UI directly to a model WITHOUT it being an MvxViewModel. However, if I bind directly to the Model returned by the web service, I lose the ability to RaisePropertyChanged() since that only comes from MvxViewModel.
Normally, I would write a ViewModel that wraps the Model and have all the wrapped setters call RaisePropertyChanged(). However, in this case, my model is dynamic so I can't wrap it with a ViewModel at compile time since I don't know what it is until runtime.
Is there some cool trick I can use to construct a ViewModel that can wrap any C# model class and send out property changed events without knowing what properties the model class has until runtime?
I just discovered the DLR and the DynamicObject which seems to be perfect, but due to Apple restrictions, it will not work on Xamarin.iOS.
Without teasing DynamicObject into life on iOS, the main approaches that think of are:
You could change your webservice generation code so that it produces INotifyPropertyChanged - I've used libraries that do this - e.g. http://stacky.codeplex.com/SourceControl/latest#trunk/source/Stacky/Entities/Answer.cs - and if you can't change the webservice code generation itself, you might still be able to wrap or pervert the generated code using some kind of t4 or other templating trick.
You could investigate some kind of code that maps the web service objects to some kind of observable collection (Kiliman has suggested this in comments)
You could look at some kind of valueconverter (or maybe valuecombiner) which does the binding - I can fairly easily imagine a valueconverter which takes a wrapped model object and a string parameter (the property name) and which uses those two together (with some reflection) to work out what to do. I'm not as sure how this one would work with nested model objects... but even that could be possible...
You could look at some kind of custom binding extension for MvvmCross. This isn't as scary as it sounds, but does require some reflection trickery - to understand what might be involved take a look at the FieldBinding plugin - https://github.com/MvvmCross/MvvmCross-Plugins/tree/master/FieldBinding
During the actual data-binding process, the plugin will be called via IMvxSourceBindingFactoryExtension - that would be your opportunity to hook into some other custom change event (rather than INotifyPropertyChanged). It might take a little experimentation to get this right... especially if you have nested objects (which then require "chaining" within the binding)... but I think it should be possible to produce something this way.
I am not sure if what I finalized on supports all possible functionality, but so far, it seems to satisfy everything that I need.
I really liked the idea of writing my own IMvxSourceBindingFactoryExtension. However, in investigating how to do that, I started playing with the functionality that already exists within MvvmCross. I already knew that MvvmCross would honor an ObservableCollection. What I didn't know was that I could use [] in my binding expressions AND that not only would integer indexers work, but also string indexers on a Dictionary. I discovered that MvvmCross sample code already has an implementation of ObservableDictionary within its GIT repo. It turns out, that is all that I needed to solve my problem.
So my model contains static properties AND an ObservableDictionary<string,object> of dynamic properties where the key is the name of the dynamic property and the value is the value of the property.
My ViewModel wraps this model class to send out PropertyChanged notifications on the static properties. Since the Dictionary of dynamic properties is observable, MvvmCross already handles changes to members of that dictionary, including 2-way.
The final issue is how to bind to it in my binding expression. That is where the [] comes in. If my ObservableDictionary property name is called UserValues and it contains a value at key user1, then I can 2-way bind to it by using: UserValues[user1] and everything seems to work perfectly.
One issue I see is that I am now requiring my dynamic data source to return an ObservableDictionary to me instead of just a Dictionary. Is that asking too much?

Converting a Library to WCF web service

As the subject line describes, I am in the process of exposing a C# library into a WCF Service. Eventually we want to expose all the functionality, but at present the scope is limited to a subset of the library API. One of the goals of this exercise is also to make sure that the WCF service uses a Request / Response message exchange pattern. So the interface /API will change as the existing library does not use this pattern
I have started off by implementing the Service Contracts and the Request/Response objects, but when it comes to designing the DataContracts, I am not sure which way to go.
I am split between going back and annotating the existing library classes with DataContract/DataMember attributes VS defining new classes which are like surrogate classes to the existing classes.
Does anyone have any experience with similar task or have any recommendations on which way works best ? I would like to point out that our team owns the existing library so do have the source code for it. Any pointers or best practices will be helpful
My recommendation is to use the Adapter pattern, which in this case basically means create brand new DataContracts and ServiceContracts. This will allow everything to vary independently, and will allow you to optimize the WCF stuff for WCF and the API stuff for the API (if that makes sense). The last thing you want is to go down the modification route and find that something just won't map right once you are almost done.
Starting from .NET 3.5 SP1 you no longer need to decorate objects that you want to expose with [DataContract]/[DataMember] attributes. All public properties will be automatically exposed. This being said personally I prefer to use special DTO objects that I expose and decorate with those attributes. I then use AutoMapper to map between the actual domain models and the objects I want to expose.
If you are going to continue to use the existing library but want to have control over what you expose as the web service API, I would recommend defining new classes as wrapper(s) around the library.
What I mean to say is don't "convert" the existing library even if you think you're not going to continue to use it in other contexts. If it has been tested and proven, then take advantage of that fact and wrap around it.

Lazy Loading with a WCF Service Domain Model?

I'm looking to push my domain model into a WCF Service API and wanted to get some thoughts on lazy loading techniques with this type of setup.
Any suggestions when taking this approach?
when I implemented this technique and step into my app, just before the server returns my list it hits the get of each property that is supposed to be lazy loaded ... Thus eager loading. Could you explain this issue or suggest a resolution?
Edit: It appears you can use the XMLIgnore attribute so it doesn’t get looked at during serialization .. still reading up on this though
Don't do lazy loading over a service interface. Define explicit DTO's and consume those as your data contracts in WCF.
You can use NHibernate (or other ORMs) to properly fetch the objects you need to construct the DTOs.
As for any remoting architecture, you'll want to avoid loading a full object graph "down the wire" in an uncontrolled way (unless you have a trivially small number of objects).
The Wikipedia article has the standard techniques pretty much summarised (and in C#. too!). I've used both ghosts and value holders and they work pretty well.
To implement this kind of technique, make sure that you separate concerns strictly. On the server, your service contract implementation classes should be the only bits of the code that work with data contracts. On the client, the service access layer should be the only code that works with the proxies.
Layering like this lets you adjust the way that the service is implemented relatively independently of the UI layers calling the service and the business tier that's being called. It also gives you half a chance of unit testing!
You could try to use something REST based (e.g. ADO.NET Data Services) and wrap it transpariently into your client code.