Different parameters type for typed factory in Castle Windsor - inversion-of-control

Given an interface like this:
public interface IFooFactory
{
IFoo Create();
void Release(IBar bar);
}
and assuming that the IFoo must implement IBar, will Castle Windsor know what to do with the object or are we creating any issues where the object types isn't exactly the same? The documentation did not say one way or other whether this is supported.

Yes it will. The declared type on the releasing method doesn't matter to Windsor. So all following methods will have the same behaviour:
void Release(IBar obj)
void ReleaseMe(IFoo obj)
void Exterminate(Object obj)
Having different types in your create and release methods may be a bit confusing to whoever will end up using your IFooFactory though.

Related

Resolving to parent interface during constructor injection

This involves autofac and c#. I have an interface derived from a parent interface:
public interface IJ4JLogger<out TCalling>
{
}
public interface IJ4JSmsLogger<out TCalling> : IJ4JLogger<TCalling>
{
}
Certain classes depend on being supplied an instance of the parent interface during construction:
public FileHistoryConfiguration( IJ4JLogger<FileHistoryConfiguration> histLogger, IJ4JLogger<FileHistoryService> svcLogger )
{
}
But if I register the type like this with autofac:
builder.RegisterGeneric( typeof(J4JSmsLogger<>) )
.As(typeof(IJ4JSmsLogger<>))
.SingleInstance();
where J4JSmsLogger<> is a class implementing IJ4JSmsLogger<>, then this call fails with an error that it can't find anything registered to provide an IJ4JLogger<> interface:
_fhConfig = _svcProvider.GetRequiredService<IFileHistoryConfiguration>();
I can work around the problem by changing the As<> clause in the registration of J4JSmsLogger<> to treat it as a IJ4JLogger<> instance, and then cast the result of resolving that interface to IJ4JSmsLogger<> whenever I need the extra capabilities of the child interface.
But I don't understand why I have to do that. Is there an additional step I need to take during registration of the types with autofac so that objects implementing the child interface will satisfy a need for the parent interface?
Cleaner Workaround
Reading more about autofac I learned something new: you can define as many As<>() clauses (including AsSelf()) as you want. So changing my autofac configuration to:
builder.RegisterGeneric( typeof(J4JSmsLogger<>) )
.As(typeof(IJ4JSmsLogger<>))
.As(typeof(IJ4JLogger<>))
.SingleInstance();
provides a cleaner solution than constantly casting resolved instances.
I'm not going to submit it as an answer, though, because I am curious why autofac doesn't do this kind of downcasting automatically, and whether any other DI frameworks do.
Autofac won't cast to base types for you like that. It generally assumes wiring is exact. You could run into some real problems if it didn't, like if someone has a constructor like...
public class BadTimes
{
public BadTimes(object input) { }
}
Which object does it put in there? Everything casts down to object.
However, you could always register it as both types and call it a day:
builder.RegisterGeneric(typeof(J4JSmsLogger<>))
.As(typeof(IJ4JSmsLogger<>))
.As(typeof(IJ4JLogger<>))
.SingleInstance();

ProtoBuf - Azure Service Fabric

I am looking at replacing the default serializer for RPC in ASF. This involves implementing a few interfaces, one of which is passed between services communicating via RPC
public interface IServiceRemotingResponseMessageBody
{
void Set(object response);
object Get(Type paramType);
}
As the implementation needs to be serializable, the obvious ProtoBuf implementation is something like
[ProtoContract]
public class ProtoBufRemotingResponseBody : IServiceRemotingResponseMessageBody
{
[ProtoMember(1)]
public object Value { get; set; }
public void Set(object response)
{
Value = response;
}
public object Get(Type paramType)
{
return Value;
}
}
Unfortunately this fails miserably with
No serializer defined for type: System.Object
Is there a workaround here? System.Object has no contract, but the OOTB DataContract serializer can, as can MessagePack here, but these are not schematized which creates versioning headaches when using reliable collections. I have tried using a common base type, but Value can be IEnumerable<T> or T etc.
Can anyone help?
Thanks,
KH
At the moment, protobuf-net does not have good support for object, except via some messy hacks. The simplest to try (just to see if it works for your scenario) is to find the "dynamic types" flag on that proto-member attribute and set it to true. This library-specific hack burns some type metadata into to data to allow it to work with unknown types, but it is far from perfect.
The "better" fix here would involve me finding the time to implement the "any" feature (added to the Google library relatively recently, around the time of proto3 IIRC). This works broadly similarly, but would be implemented in a cross-library way.

eclipse null analysis field initialization

Using the Null Analysis of Eclipse:
It it possible to define other methods as initializing methods than Constructors?
I have a class like this:
public class Foo {
#NonNull
private Object fooObject;
public Foo() {
super();
}
public void onCreate() {
fooObject = //Something which is not available in the Constructor;
}
Here i get the warning that the NonNull field may has not been initialized. Is there any possibility to kind of declare the init-method as an initalizing one?
I could use #SuppressWarnings("null") for the constructor. But then I ignore all fields, which may instanciated somewhere.
Second chance i see is to make fooObject as #Nullable - but then i need check for null each time i use fooObject.
So is there any better solution?
Null-checking object initialization beyond the constructor is inherently difficult. Several sophisticated approaches exist, all of which require additional annotations.
In your example it seems to be near-impossible, to prove to the compiler, that onCreate() is always called before accessing the field.
A weaker solution has been proposed: #LazyNonNull, an annotation to be used on fields that are initially null, but once initialized can never go back to null. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=414237
Obviously, a static factory method, that gathers all necessary values before invoking a constructor (with arguments) would be a lot easier to get right.

Is there a difference between SimpleIoc.Default.GetInstance and ServiceLocator.Current.GetInstance

I am using version 4 of MVVM Light for Windows 8; it includes SimpleIOC. In various examples I sometimes see code to request an object based on SimpleIoc... and sometimes it is based on ServiceLocator...
Examples include:
userToken = SimpleIoc.Default.GetInstance();
mainVM = ServiceLocator.Current.GetInstance();
What is the difference between using SimpleIoc.Default.GetInstance and ServiceLocator.Current.GetInstance?
If there is no difference, does ServiceLocator just let me to have an option to change my mind about what IOC library I want to use? Does ServiceLocator just provide an additional layer of abstraction that is irrelevant if I am satified with SimpleIoc; or, does ServiceLocator perform some other useful magic that is not obvious to we IOC novices?
Thanks for the insight!
In your ViewModelLocator class you probably have the following line of code:
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc implements the IServiceLocator interface, which means that the ServiceLocator will use it as a DI source when invoked.
Edit:
OK, people want the "full fat and don't spare the cream" answer. Here we go!
ServiceLocator is basically a shell. The code for Service locator is:
public static class ServiceLocator
{
private static ServiceLocatorProvider currentProvider;
public static IServiceLocator Current
{
get
{
return ServiceLocator.currentProvider();
}
}
public static void SetLocatorProvider(ServiceLocatorProvider newProvider)
{
ServiceLocator.currentProvider = newProvider;
}
}
Yup, that's it.
What's ServiceLocatorProvider? It's a delegate that returns an object that implements IServiceLocator.
SimpleIoc Implements IServiceLocator. So when we do:
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
We put our SimpleIoc object into the ServiceLocator. You can use either of these now because whether you call ServiceLocator.Current or SimpleIoc.Default you're returning the same object instance.
So, is there any difference between
userToken = SimpleIoc.Default.GetInstance();
mainVM = ServiceLocator.Current.GetInstance();
?
Nope. None. Both are singletons exposing a static property that is an implementation of IServiceLocator. As mentioned above, you're returning the same instance of object that implements IServiceLocator regardless of which you call.
The only reason why you might want to user ServiceLocator.Current.GetInstance() rather than SimpleIoc.Default.GetInstance() is that at some point in the future you may change DI containers and, if you use ServiceLocator, you won't have to change your code.
Based on Mr. Bugnion's article on MSDN (in the section, "Various Ways to Register a Class"), I am presuming interchangeability of IoC providers is the one and only reason for using ServiceLocator.
As #FasterSolutions stated, SimpleIoc implements IServiceLocator, so I suspect the opposite to your statement about abstraction layers is true. I think you should use ServiceLocator, but this is without empirical evidence; maybe someone can prove me wrong (?)

interface class in Managed C++

The interfaces in Managed C++ looka bit strange to me since they allow static methods and members inside them. For example, following is a valid MC++ interface.
interface class statinterface
{
static int j;
void Method1();
void Method2();
static void Method3()
{
Console::WriteLine("Inside Method 3");
}
static statinterface()
{
j = 4;
}
};
Well, my question is that what is the use of static methods in an interface. And what happened to virtual tables etc. What will be the virtual table of the classes implementing this interface. There are lots of questions that come to mind. This type of class i.e., interface class is not equivalent to a plain abstract class since we can't have definition of non-static methods here.
I just want to know the wisdom of allowing statics in interface. This is certainly against OOP principles IMO.
The easiest way to answer this question is to use .NET Reflector to examine the assembly generated from the code.
A VTable only ever contains virtual functions, so statics simply wouldn't be included.
The language is called C++/CLI, not Managed C++ (that was something bad from way back in 2002).
This has nothing to do with OOP principles, which originally never included the concept of a pure interface anyway.