Is there an OOB way in Ninject to configure service in singleton scope? - ninject

I am using ninject with ninject.extenions.conventions. I would like to use a convention to initialize some services as singletons. I know it is straightforward to add a SingletonAttribute and use it with .WithAttribute<SingletonAttribute>() during configuration. But I don't want to reinvent the wheel.

There's no singleton attribute being deliver with Ninject or ninject conventions.
The question is how you want to determine which types are bound .InSingletonScope(). Instead of an attribute you could also filter for types whose name end's with Service. Or which implement a specific interface. or which implement a specific attribute.
I would consider going for a name-based convention, if that does make sense. If not, you'll have to decide between shared interface or an attribute. If there's no shared methods/properties then a marker interface (empty interface) does not make sense and you should go with attributes.

Related

How to wrap class properties?

there is a conceptional question:
I want to have a wrapper class which forwarding all called selectors to a given object. How do I do this?
And here is why:
I have a library for synchronizing data with a service. And I use Core Data.
For the library I have to create classes of a specific protocol. But I can not use the same protocol for the Core Data subclasses.
My idea is to create a subclass of the specific protocol and forwarding the protocol calls to the Core Data Object.
But there are many subclasses and many properties per subclass and without changing the Core Data subclasses (project specific requirement!)
Is there a way to do this without overwriting every method?
Thanks for your time =)
Implement -forwardingTargetForSelector:. You can return another object to forward unknown messages to. If that is most of what your class will do, you may want to just subclass from NSProxy rather than NSObject. (NSProxy has the advantage that it doesn't implement all of the standard NSObject methods, so you can forward those as well.)
One common problem with this approach is that the compiler will complain that your class does not respond to the selectors you're sending it. The usual way to address this is by requiring that users of your object declare it as id. This can often be inconvenient as well, so this is a bit of a last resort if other approaches are not possible.
But usually the better approach is to make your class a subclass of the target and add the additional methods required for your protocol. Or you can add the additional methods to the Core Data class via a category.
The answer to your specific question is yes. Message Forwarding contains everything you need.
I think you might want to step back and evaluate other options. For example, can you add this functionality to a base class instead of a proxy class.

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.

Windsor Typed Factory facility, passing arguments when using singleton lifestyle

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.

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.

WCF Web Service Bloat

I am developing a WCF web service which has become quite bloated. What techniques do you use to split up the implementation of the contract?
Well you have a couple choices:
First, you could leave it all in one class, but split up into different files using the partial class feature of C#.
Second, you could have the main service class just pass requests off to one of a number of other actual classes that are organized logically.
A third alternative is to consider refactoring to reduce the number of operations you have. Is there actually a use to all of the methods you're exposing?
Finally, you could always split up the service into multiple WCF services.
It's hard to answer your question if you don't give any more information.
Do you mean that your service interface is bloated, or the class implementation? It's hard to answer well, if I don't see the code, or have no other information, anyway, I'll try:
Notice that WCF service is basically just a regular class that implements an interface and has some attributes on its methods. So all the other good OO design rules apply to it. Think about what it does, does it have really single responsibility, if not try to outsource some of that responsibility to other classes that your service depends on. If you need a non-default constructor, use IInstanceProvider to create the service class, and supply it with its dependencies (or if you use Windsor Container use WCF Facility).
If you really want to you can streach your inheritance chain, and move some of the code to a base class. I don't do it, however and always prefer to use composition over inheritance.
Inspect your service contract, and think about how cohesive it really is. Maybe what you should do is to split it, into few smaller, more cohesive services.