Use NInject to initialize several collections - c#

I apologize in advance if this is a dumb question: I am quite new to NInject.
I need to initialize my application with several collections, each having several identical objects. Without IoC, that would look like:
public ICollection<ICollection<IBusinessObject>> Piles = new ICollection<ICollection<IBusinessObject>>();
public MyCollectionContainer()
{
Piles.Add(new List<IBusinessObject>({ new ObjectA(), new ObjectA() });
Piles.Add(new List<IBusinessObject>({ new ObjectB(), new ObjectB() });
Piles.Add(new List<IBusinessObject>({ new ObjectC(), new ObjectC() });
}
I'd like to instruct NInject to do that job for me, so that a call to Kernel.Get<MyCollectionContainer>() would do the same job as above, with some extra flexibility, of course.
In other words, I want, at bind time, to instruct NInject to
Kernel.Bind<ICollection<ICollection<IBusinessObject>>>().To< /* A list of 3 */>();
Kernel.Bind<IList<IBusinessObject>>().To< /* A List of 2 IBusinessObject */>();
Kernel.Bind<IBusinessObject>().To< /* a different type depending on the container */>();
Side question: Should I better use Kernel.Get<MyCollectionContainer>() or Kernel.Get<ICollection<ICollection<IBusinessObject>>>()
EDIT: While searching for a solution, I tried to define a custom binding for my collections in the model of
Kernel.Bind<IList<IBusinessObject>>()
.ToConstructor(x => new List<IBusinessObject>(
x.Inject<IList<IBusinessObject>>())
);
With an extension method IConstructorArgumentSyntax.InjectMany(int i):
Kernel.Bind<IList<IBusinessObject>>().To<ObjectA>();
Kernel.Bind<IList<IBusinessObject>>()
.ToConstructor(x => new List<IBusinessObject>(
x.InjectMany<IList<IBusinessObject>>(2))
);
public static T InjectMany<T>(this IConstructorArgumentSyntax x, int numberOfInjections)
{
/* loop */
{
x.Inject<T>();
}
}
Sadly NInject refuses to call x.Inject(); complaining that I've dived too deep into their magic:
System.InvalidOperationException :
This method is for declaration that a parameter shall
be injected only! Never call it directly.

Related

Dynamically creating Objects at runtime with parameters DI vs Factory

I currently have a case where I have multiple customers who have variability of on what forms of notifications they want (ie email, fax, etc.). They could also want one or more than one. So I have created a factory with some basic Reflection that will dynamically create concrete classes depending on some parameters that get sent in through the customer profile. I'm curious is there a better way to do this using ASP.Net Core Dependency Injection? I have put in the factory code here to help folks understand of what I'm trying to do.
The customer profile will send in a string array of what services they have subscribed as a parameter to CreateInstances so only specific services would be dynamically created.
public Dictionary<string, Type> Notifications;
public NotificationFactory()
{
LoadTypes();
}
public IEnumerable<INotificationService> CreateInstances(params string[] namesOfServices)
{
var servicesToInstantiate = namesOfServices.ToList();
List<INotificationService> result = new List<INotificationService>();
foreach (var service in servicesToInstantiate)
{
Type serviceName = GetServiceNameToCreate(service.ToLower());
if (serviceName != null)
{
result.Add(Activator.CreateInstance(serviceName) as INotificationService);
}
}
return result;
}
private Type GetServiceNameToCreate(string NotificationClassName)
{
return Notifications.FirstOrDefault(a => a.Key.Contains(NotificationClassName)).Value;
}
protected virtual void LoadTypes()
{
Notifications = Assembly.GetExecutingAssembly().GetTypes()
.Where(t => typeof(INotificationService).IsAssignableFrom(t) && !t.IsInterface)
.ToDictionary(t => t.Name.ToLower(), t => t);
}
It is a bad idea to take an arbitrary string and activate an instance the way you are doing it. The string should at least be white-listed. If a malicious user were able to tamper with the strings in the database, for example, they could choose what type to activate and potentially trigger unauthorized behavior or denial of service.
Instead, define a white list of types, and associate each type with a delegate that constructs the service you need.
var map = new Dictionary<string,Func<INotificationService>>
{
{ "EMAIL" : () => new EmailService() },
{ "PHONE" : () => new PhoneService() }
};
Then to get a service, call
if (!map.ContainsKey(serviceType)) throw new ArgumentException(nameof(serviceType));
INotificationService service = map[serviceType]();
Or if you prefer:
Func<INotificationService> factory;
if (!map.TryGetValue(serviceType, out factory)) throw new ArgumentException(nameof(serviceType));
INotificationService service = factory();
This way you are certain that the service type is one that you support, and you don't need to use any Reflection.
If you need more extensibility
If you want to be able to add more delivery methods without changing the code that populates map, you can of course populate the map from a configuration file. Although I'm left wondering how you could possibly implement a new delivery method without changing any code, and whether you have a bone fide NFR that requires you to be able to. Seems to me that new delivery methods don't get added very often and would be a big deal in other respects, so there is little point in saving yourself adding one line of code here.

Adapter/Wrapper and equal references

I want to create a wrapper class for another type. This works fine until the point where it's necessary that (reference)-equal objects need to have (reference)-equal wrappers.
An example:
public interface ITest<T>
{
T GetInstance(bool createNew);
}
public class Test : ITest<Test>
{
private static Test instance;
public Test GetInstance(bool createNew)
{
if (instance == null || createNew)
{
instance = new Test();
}
return instance;
}
}
public class TestWrapper : ITest<TestWrapper>
{
private readonly Test wrapped;
public TestWrapper(Test wrapped)
{
this.wrapped = wrapped;
}
public TestWrapper GetInstance(bool createNew)
{
return new TestWrapper(wrapped.GetInstance(createNew));
}
}
Test.GetInstance returns always the same instance, as long as the parameter createNew is false.
By contrast TestWrapper.GetInstance returns always a new instance.
Since I want to be able to replace Test with TestWrapper, I search for a solution so that at the end, the wrapper returns a new instance only, if Test returns a new instance. However, the TestWrapper should have no knowledge about the internals of Test.
The test code is
private static void RunTest<T>(ITest<T> cls)
{
var i1 = (ITest<T>)cls.GetInstance(false);
var i2 = (ITest<T>)cls.GetInstance(false);
var i3 = (ITest<T>)cls.GetInstance(true);
var dic = new Dictionary<ITest<T>, bool>();
if (!dic.ContainsKey(i1)) dic.Add(i1, false); else dic[i1] = true;
if (!dic.ContainsKey(i2)) dic.Add(i2, false); else dic[i2] = true;
if (!dic.ContainsKey(i3)) dic.Add(i3, false); else dic[i3] = true;
Console.WriteLine(string.Join(", ", dic.Select(a => a.Value.ToString())));
}
The desired result is
True, False
and that's what you get if one passes new Test() to that method.
If you pass new TestWrapper(new Test()), you'll get
False, False, False
There is a solution based on a simple cache (Dictionary<Test, TestWrapper>) - but with that, I would hold many of the instances in memory without using them any further (and the GC could not collect those instances since there's a reference holding them).
I played around with WeakReferences a bit, but I can't spot a key that I can use to store the WeakReference - thus I have to iterate through the cache list and search for the correct instance which is slow. Besides, I've to implement this solution for every member (with it's very own cache) which seems not to be a great solution...
I hope I have adequately explained my problem ;) So, my questions are:
is there a way to cheat object.ReferenceEquals (that question is unrewarding)
what can I use (as a key for the cache) as an identifier for an object instance (so I can use WeakReference)
is there a better way to achieve a real adapter (where I can replace the adaptee with an adapter without headache)
I've no access to the Test class, and only limited access to the code that uses it (I'm able to pass an arbitrary instance as long it's implements the interface)
No, you can't cheat object.ReferenceEquals(). However, object.ReferenceEquals() is intentionally used very rarely, and usually in cases where things really do need to be reference-equal.
The runtime need it in order to get things right. E.g. if the instance is used as a key in an Dictionary<>
Actually, the runtime typically uses the .GetHashCode() and .Equals() behavior of the individual objects, but it just so happens that if you don't override that behavior in your classes, the base System.Object implementation of those methods relies on the object reference by default.
So if you have the ability to change the code for both the Test class and the TestWrapper class, you can override these equality methods in those classes to ensure that they recognize equivalent objects as equal.
An alternative (and usually better) approach would be to create an IEqualityComparer<> implementation to use in your specific use case. You mentioned keys in a Dictionary<>: you can provide an IEqualityComparer<> instance to the dictionary when it's created to have it test for equality in exactly the way you want.
var dict = new Dictionary<object, object(new TestsAndWrappersAreEqualComparer());
var test = Test.GetInstance(true);
var testWrapper = TestWrapper.GetInstance(true);
dict[test] = test;
Console.WriteLine(dict.ContainsKey(test)); // true

I created two constructors but can only create an instance using one of them

EDIT:
I am working with company property here and the concept is something that should make sense to the people reading this post:
I have 2 constructors for EFImport, one has 2 arguments the other has 3 arguments. What I am suggesting is that my constructor with 2 arguments is not being recognized. I am using the new keyword, and am initializing the object in the exact same manner with the constructor that has 3 arguments and it works perfectly. BUT the constructor with 2 arguments is not being identified. Again, I cannot specifically put up the code here but the concept is what I am asking about.
I have a need to use two different constructors, one that takes an extra argument, and one that does not need that argument. I am not sure exactly why I am not able to actually reach the constructor that has only two arguments.
I have the following constructors:
public EFImport(string empId, Class A instanceA, IEnumerable<ClassB> instanceB)
{
//do stuff here
}
public EFImport(string empId, Class A instanceA)
{
//do other different stuff here
}
I am trying to call the constructors like this:
Public HttpResponseMessage Post([FromBody]string fEmp)
{
//do stuff here
//call constructor here:
//NEW keyword is used here
var fileImp = new EFImport(empId, instanceA, instanceB);
//this works just fine
}
Public HttpResponseMessage Put([FromBody]string empImportId)
{
//do stuff here
//call constructor here:
//NEW keyword used here
var fileImp = new EFImport(empId, instanceA);
//Here it gives me the error stated below
}
Error 509 'EFImport' does not contain a constructor that takes 2 arguments
What exactly am I doing wrong? Both constructors are public and the constructor with 3 arguments works perfectly fine, but the compiler does not see the constructor taking 2 arguments. Am I overlooking something really simple?
var obj = new EFImport(empId, instanceA);
and
var obj = new EFImport(empId, instanceA, instanceB);
should work.
I don't seem to know what you are doing with:
var EFImport(empId, instanceA)
You have a few issues with this code:
You are instantiating the object incorrectly. In C# if you want to create a new object you would use:
TypeOfVar nameOfVar = new TypeOfVar();
or
var nameOfVar = new TypeOfVar();
More information on how to use constructors in C# can be found at: https://msdn.microsoft.com/en-us/library/ace5hbzh.aspx
You also seem to be missing your semicolons ;)

Creating a new instance of an object each time method is called

Messenger.Default.Register<OpenWindowMessage>(this, message =>
{
var adventurerWindowVM = SimpleIoc.Default.GetInstance<AdventurerViewModel>();
adventurerWindowVM.Adv = message.Argument;
var adventurerWindow = new AdventurerView()
{
DataContext = adventurerWindowVM
};
adventurerWindow.Show();
});
This code is fairly simple; it just opens a new window and sets the DataContext of the new window. The problem I'm having is that if I execute this twice, the content of the first instance will be overwritten and be set to that of the second since adventurerWindowVM is the DataContext of both windows and it is overwritten each time this code is called. I'm looking for a way to prevent this; I'd like to be able to open multiple windows using this message and have each of them be unique, but thus far I haven't figured out a way to do so. Any advice would be greatly appreciated. I apologize for the vague title; I was unsure of what to name this question. (Also, I know that this isn't a method. What would this block of code be called?)
Update: I'm using MVVM Light and my code is based off of an example somebody provided for me in this answer: https://stackoverflow.com/a/16994523/1667020
Here is some code from my ViewModelLocator.cs
public ViewModelLocator()
{
_main = new MainViewModel();
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<GameViewModel>();
SimpleIoc.Default.Register<AdventurerViewModel>();
}
Having given the other answer, I guess I can say the IoC container used here is just SimpleIoC from MvvmLight and to get a new instance of the VM on every GetInstance(...) all you need to do is pass in a unique key every time when trying to resolve an instance of the VM.
So you can switch
var adventurerWindowVM = SimpleIoc.Default.GetInstance<AdventurerViewModel>();
to
var adventurerWindowVM = SimpleIoc.Default.GetInstance<AdventurerViewModel>(System.Guid.NewGuid().ToString());
However as mentioned by the author of MVVMLight Here these VM's will get cached and we need to get rid of them when no longer needed. In your case probably when the Window is closed.
Thus I'd have that entire lambda something like:
Messenger.Default.Register<OpenWindowMessage>(this, message =>
{
var uniqueKey = System.Guid.NewGuid().ToString();
var adventurerWindowVM = SimpleIoc.Default.GetInstance<AdventurerViewModel>(uniqueKey);
adventurerWindowVM.Adv = message.Argument;
var adventurerWindow = new AdventurerView()
{
DataContext = adventurerWindowVM
};
adventurerWindow.Closed += (sender, args) => SimpleIoc.Default.Unregister(uniqueKey);
adventurerWindow.Show();
});
Note:
While this is somewhat longer 3 lines compared to just creating a new VM yourself with (new AdventurerViewModel()) I still favor this because if you use an IoC container to manage LifeTime of your VM's, then have it manage them completely. Don't really like mix-n-match when not needed. Rather keep the IoC Container doing what it's meant to do.
If you need more control over VM injection and Life-time management look at more sophisticated Ioc controllers such as Unity. SimpleIoC was just meant to be a simple get your feet "wet" in IoC kind of container and it does a very good job in that regard.
I think you are trying to use the same instance of your ViewModel with multiple views. So the views will obviously overwrite each others viewmodel contents.
What if you do this;
Messenger.Default.Register<OpenWindowMessage>(this, message =>
{
var adventurerWindowVM = new AdventurerViewModel();
adventurerWindowVM.Adv = message.Argument;
var adventurerWindow = new AdventurerView()
{
DataContext = adventurerWindowVM
};
adventurerWindow.Show();
});
It's a method call, passing in an anonymous method using a lambda expression.
It looks like you are getting your AdventurerViewModel from some sort of IoC container. How is the IoC container configured? In particular, what is the scope of the objects it gives you back? If you have the IoC configured to create objects in singleton scope, for example, then you will always get back a reference to the same object each time. You may need to configure the scope of the object in your IoC container so that it gives you back a fresh copy every time.
How you do that will depend on your IoC container. Without knowing which IoC framework you are using or seeing its configuration, it's impossible to make any further comment.
My advice would be to create an extension method for SimpleIOC. Something like this:
public static T CreateInstance<T>(this SimpleIoc simpleIoc)
{
// TODO implement
}
You already know the method to get the same instance; extended SimpleIoc with a method to create a new instance:
T instance = SimpleIoc.Default.GetInstance<T>();
T createdInstance = SimpleIoc.Defalt.CreateInstance<T>();
If you are not familiar with extension methods, see Extension Methods Demystified
The implementation:
Of type T, get the constructor.
If there is more than one constructor: either throw exception, or decide which constructor to use. Simple method: use the same method that is used in SimpleIoc.GetInstance, with an attribute. More elaborate method: try to find out if you can find registered elements that match one of the constructors. This is not explained here.
Once you've found the constructor that you need, get its parameters.
Ask SimpleIoc for instances of this parameter, or if they should be new also, ask SimpleIoc to create new instances.
CreateInstance
.
public static T CreateInstance<T>(this SimpleIoc ioc)
{
return (T)ioc.CreateInstance(typeof(T));
}
public static object CreateInstance(this SimpleIoc ioc, Type type)
{
ConstructorInfo constructor = ioc.GetConstructor(type);
IEnumerable<object> constructorParameterValues = ioc.GetParameters(constructor);
constructor.Invoke(constructorParameterValues.ToArray());
}
To decide which constructor to use:
private static ConstructorInfo GetConstructor(this SimpleIoc ioc, Type type)
{
ConstructorInfo[] constructors = type.GetConstructors();
ConstructorInfo constructorToUse;
if (constructorInfo.Length > 1)
{
// Decide which constructor to use; not explained here
// use Attribute like SimpleIoc.GetInstance?
// other method: use SimpleIoc.IsRegistered to check which Parameters
// are registered: use ConstructorInfo.GetParameters()
constructorToUse =
}
else
constructorToUse = constructoInfo[0];
return constructorToUse;
}
To get the values of the parameters in the constructor, we need to decide whether we want existing values from Ioc, or create new values:
public static IEnumerable<object> GetParameterValues(this simpleIoc ioc,
ConstructorInfo constructor)
{
IEnumerable<Type> parameterTypes = contructor.GetParameters()
.Select(parameter => parameter.ParameterType);
return ioc.GetInstances(parameterTypes);
}
public static IEnumerable<object> GetInstances(this SimpleIoc ioc,
IEnumerable<Type> types)
{
// TODO: decide if we want an existing instance from ioc,
// or a new one
// use existing instance:
return types.Select(type => ioc.GetInstance(type));
// or create a new instance:
return types.Select(type => ioc.CreateInstance(type));
}
This seems like a lot of code, but most of it is comment and most methods are one liners.

Change object type at runtime maintaining functionality

Long story short
Say I have the following code:
// a class like this
class FirstObject {
public Object OneProperty {
get;
set;
}
// (other properties)
public Object OneMethod() {
// logic
}
}
// and another class with properties and methods names
// which are similar or exact the same if needed
class SecondObject {
public Object OneProperty {
get;
set;
}
// (other properties)
public Object OneMethod(String canHaveParameters) {
// logic
}
}
// the consuming code would be something like this
public static void main(String[] args) {
FirstObject myObject=new FirstObject();
// Use its properties and methods
Console.WriteLine("FirstObject.OneProperty value: "+myObject.OneProperty);
Console.WriteLine("FirstObject.OneMethod returned value: "+myObject.OneMethod());
// Now, for some reason, continue to use the
// same object but with another type
// -----> CHANGE FirstObject to SecondObject HERE <-----
// Continue to use properties and methods but
// this time calls were being made to SecondObject properties and Methods
Console.WriteLine("SecondObject.OneProperty value: "+myObject.OneProperty);
Console.WriteLine("SecondObject.OneMethod returned value: "+myObject.OneMethod(oneParameter));
}
Is it possible to change FirstObject type to SecondObject and continue to use it's properties and methods?
I've total control over FirstObject, but SecondObject is sealed and totally out of my scope!
May I achieve this through reflection? How? What do you think of the work that it might take to do it? Obviously both class can be a LOT more complex than the example above.
Both class can have templates like FirstObject<T> and SecondObject<T> which is intimidating me to use reflection for such a task!
Problem in reality
I've tried to state my problem the easier way for the sake of simplicity and to try to extract some knowledge to solve it but, by looking to the answers, it seems obvious to me that, to help me, you need to understand my real problem because changing object type is only the tip of the iceberg.
I'm developing a Workflow Definition API. The main objective is to have a API able to be reusable on top of any engine I might want to use(CLR through WF4, NetBPM, etc.).
By now I'm writing the middle layer to translate that API to WF4 to run workflows through the CLR.
What I've already accomplished
The API concept, at this stage, is somehow similar to WF4 with ActivityStates with In/Out Arguments and Data(Variables) running through the ActivityStates using their arguments.
Very simplified API in pseudo-code:
class Argument {
object Value;
}
class Data {
String Name;
Type ValueType;
object Value;
}
class ActivityState {
String DescriptiveName;
}
class MyIf: ActivityState {
InArgument Condition;
ActivityState Then;
ActivityState Else;
}
class MySequence: ActivityState {
Collection<Data> Data;
Collection<ActivityState> Activities;
}
My initial approach to translate this to WF4 was too run through the ActivitiesStates graph and do a somehow direct assignment of properties, using reflection where needed.
Again simplified pseudo-code, something like:
new Activities.If() {
DisplayName=myIf.DescriptiveName,
Condition=TranslateArgumentTo_WF4_Argument(myIf.Condition),
Then=TranslateActivityStateTo_WF4_Activity(myIf.Then),
Else=TranslateActivityStateTo_WF4_Activity(myIf.Else)
}
new Activities.Sequence() {
DisplayName=mySequence.DescriptiveName,
Variables=TranslateDataTo_WF4_Variables(mySequence.Variables),
Activities=TranslateActivitiesStatesTo_WF4_Activities(mySequence.Activities)
}
At the end of the translation I would have an executable System.Activities.Activity object. I've already accomplished this easily.
The big issue
A big issue with this approach appeared when I began the Data object to System.Activities.Variable translation. The problem is WF4 separates the workflow execution from the context. Because of that both Arguments and Variables are LocationReferences that must be accessed through var.Get(context) function for the engine to know where they are at runtime.
Something like this is easily accomplished using WF4:
Variable<string> var1=new Variable<string>("varname1", "string value");
Variable<int> var2=new Variable<int>("varname2", 123);
return new Sequence {
Name="Sequence Activity",
Variables=new Collection<Variable> { var1, var2 },
Activities=new Collection<Activity>(){
new Write() {
Name="WriteActivity1",
Text=new InArgument<string>(
context =>
String.Format("String value: {0}", var1.Get(context)))
},
new Write() {
//Name = "WriteActivity2",
Text=new InArgument<string>(
context =>
String.Format("Int value: {0}", var2.Get(context)))
}
}
};
but if I want to represent the same workflow through my API:
Data<string> var1=new Data<string>("varname1", "string value");
Data<int> var2=new Data<int>("varname2", 123);
return new Sequence() {
DescriptiveName="Sequence Activity",
Data=new Collection<Data> { var1, var2 },
Activities=new Collection<ActivityState>(){
new Write() {
DescriptiveName="WriteActivity1",
Text="String value: "+var1 // <-- BIG PROBLEM !!
},
new Write() {
DescriptiveName="WriteActivity2",
Text="Int value: "+Convert.ToInt32(var2) // ANOTHER BIG PROBLEM !!
}
}
};
I end up with a BIG PROBLEM when using Data objects as Variables. I really don't know how to allow the developer, using my API, to use Data objects wherever who wants(just like in WF4) and later translate that Data to System.Activities.Variable.
Solutions come to mind
If you now understand my problem, the FirstObject and SecondObject are the Data and System.Activities.Variable respectively. Like I said translate Data to Variable is just the tip of the iceberg because I might use Data.Get() in my code and don't know how to translate it to Variable.Get(context) while doing the translation.
Solutions that I've tried or thought of:
Solution 1
Instead of a direct translation of properties I would develop NativeActivites for each flow-control activity(If, Sequence, Switch, ...) and make use of CacheMetadata() function to specify Arguments and Variables. The problem remains because they are both accessed through var.Get(context).
Solution 2
Give my Data class its own Get() function. It would be only an abstract method, without logic inside that it would, somehow, translate to Get() function of System.Activities.Variable. Is this even possible using C#? Guess not! Another problem is that a Variable.Get() has one parameter.
Solution 3
The worst solution that I thought of was CIL-manipulation. Try to replace the code where Data/Argument is used with Variable/Argument code. This smells like a nightmare to me. I know next to nothing about System.reflection.Emit and even if I learn it my guess is that it would take ages ... and might not even be possible to do it.
Sorry if I ended up introducing a bigger problem but I'm really stuck here and desperately needing a tip/path to go on.
This is called "duck typing" (if it looks like a duck and quacks like a duck you can call methods on it as though it really were a duck). Declare myObject as dynamic instead of as a specific type and you should then be good to go.
EDIT: to be clear, this requires .NET 4.0
dynamic myObject = new FirstObject();
// do stuff
myObject = new SecondObject();
// do stuff again
Reflection isn't necessarily the right task for this. If SecondObject is out of your control, your best option is likely to just make an extension method that instantiates a new copy of it and copies across the data, property by property.
You could use reflection for the copying process, and work that way, but that is really a separate issue.

Categories

Resources