How do you store these generic parameters? - c#

I am working with ServiceStack. This library has a method for dependency injection, called Register.
public IRegistration<TService> Register<TService>(TService> instance)
Which you call like this:
Container.Register<IFirstServiceInterface>(new FirstServiceInterfaceImplementation());
Container.Register<ISecondServiceInterface>(new SecondServiceInterfaceImplementation());
Now, I want to create a method which takes the same parameters as Register. In my method however, I would add the passed instance and interface type to an ICollection object, to pass it to ServiceStack's Register method at a later point in time. At the time I want to pass these parameters to ServiceStack, I would simply call:
foreach(var item in dependencyCollection)
{
ServiceStack.Register(item);
//not exactly how you call the Register method, but you get the idea.
}
How would I set up a collection object to achieve the result I'm looking for? I'm having trouble storing both an interface type, and an implementation for it.

It's hard to infer what you're looking for here, but maybe you're looking at some of ServiceStack Funq's IOC late-bound API's? e.g:
container.Register(
new FirstServiceInterfaceImplementation(),
typeof(IFirstServiceInterface));
//or
container.RegisterAutoWiredType(
typeof(FirstServiceInterfaceImplementation),
typeof(IFirstServiceInterface));
In which to use the first API you can use a Dictionary<Type,object>, e.g:
var deps = new Dictionary<Type,object> {
{ typeof(IFirstServiceInterface), new FirstServiceInterfaceImplementation() },
{ typeof(ISecondServiceInterface), new SecondServiceInterfaceImplementation() },
};
Then register like:
foreach (var entry in deps)
{
container.Register(entry.Value, entry.Key);
}

Related

C# method syntax similar to object initializer

We have an extension method that accepts an action to initialize an object.
Is there some way to improve the syntax of such a call:
public static T NewRow<T>(this IUow uow, Action<T> action();
// this does internally call
public T NewRow<T>(Action<T> initializer) where T : IBo
{
T bo = NewRow<T>();
initializer.Invoke(bo);
return bo;
}
uow.NewRow<ICustomer>(customer => {
customer.Name = "Zzz";
customer.Info = "Abc"
);
I thought maybe I could use something similar to the object initializer syntax?
uow.NewRow<ICustomer>({
Name: "Zzz",
Info: "Abc"
});
The idea is to get rid of customer.* = ... in every line.
I would be happy for any tip.
INFO:
We are using the latest C# language version
The solution should support IntelliSense (e.g., Name and Info should be proposed to the user)
Edit:
I can't use a constructor because I only have an interface. No class/implementation. The framework behind creates the object to the given interface T bo = NewRow<T>();. Which actual object gets created is decided by the framework
Also initializers like { Name: myOtherVariable.FirstName } should be possible
an Action could be everything, not just a simple assignment. So if a client chosed to make a function-call instead, there literally is nothing to shortcut here. See this for example:
uow.NewRow<IWhatever>(() => Console.WriteLine("tataaaa"););
So no, what you want isn't possible.
However you could create some kind of EventsArgs that hold your names and use those within your NewRow-method. There's no need for an action if all those callbacks should actually be just assignement-calls alltogether.
uow.NewRow<ICustomer>(new MyArgs {
Name = "Zzz",
Info = "Abc"
});
And within NewRow:
public T NewRow<T>(MyArgs args) where T : IBo
{
customer.Name = args.Name;
customer.Info = args.Info;
}

Microsoft Unity 3.0 DI with Lazy<List<IFoo>> does not work

I have following configuration in my code with which a view is configured as a IWorkflowModule:
dependencyContainer.RegisterType<IWorkflowModule, StartView>();
I would like to get all these IWorkflowModule implementation as constructor parameters of another class. This class is instantiated after the registration of the modules.
public WorkflowConfigReader(Lazy<List<IWorkflowModule>>
availableWorkflowModules)
{
this.availableWorkflowModules = availableWorkflowModules;
}
The parameter of the constructor is Lazy because I will use the modules some time later on and want to be sure that they are registred before. I also need them as a list to get all the modules.
Unfortuanatly, I get an empty list if I do it this way. I am not sure but I guess Unity does not support dependency injection for a IEnumerable which is not staticly configured. Is this correct? Are there any solutions for this?
Thank you.
You need to tell Unity what you want when a List<IWorkflowModule> is requested. So you could do something like:
IUnityContainer container = new UnityContainer();
// Default registration if required
container.RegisterType<IWorkflowModule, StartView>();
// IEnumerable Registration
container.RegisterType<IWorkflowModule, StartView>("WorkflowConfigReaderItem1");
container.RegisterType<IWorkflowModule, EndView>("WorkflowConfigReaderItem2");
container.RegisterType<List<IWorkflowModule>>(new InjectionFactory(c =>
{
return c.ResolveAll<IWorkflowModule>().ToList();
}));
Unity does know how to resolve arrays so if you were to use an array of IWorkflowModule then you wouldn't have to register an InjectionFactory:
public WorkflowConfigReader(Lazy<IWorkflowModule[]>
availableWorkflowModules)
{
this.availableWorkflowModules = availableWorkflowModules;
}
// Default registration if required
container.RegisterType<IWorkflowModule, StartView>();
container.RegisterType<IWorkflowModule, StartView>("WorkflowConfigReaderItem1");
container.RegisterType<IWorkflowModule, EndView>("WorkflowConfigReaderItem2");
var configReader = container.Resolve<WorkflowConfigReader>();

Library to generate class that has inline constructor in another assembly with random data?

I'm receiving event notifications from web services that trigger event handlers with data regarding what triggered the event. I'm trying to test that once an event handler is called that a, b and c are all called with the proper values. This isn't possible without relying on the web service
My solution is to create converters that convert the EventArgs that are returned to my via the services library (Exchange Web Services) to something my dumb objects can understand without relying on third part services. My issue is that the EventArgs class given to my by the EWS library has an internal constructor so there's no easy way to generate an instance of it with random property values without much work with reflection.
For example, I have a simply interface:
public interface IConverter<TFrom, TTo>
{
TTo Convert(TFrom from);
}
and a simple implementation:
public class NotificationEventArgsConverter : IConverter<NotificationEventArgs, NewNotification>
{
public NewNotification Convert(NotificationEventArgs from)
{
return new NewNotification
{
ItemIds = from.Events.Cast<ItemEvent>().Select(x => x.ItemId.ToString())
};
}
}
Question is how can I generate an instance of NotificationEventArgs with random values. Is there a library for this that I missed in my searches?
The entire goal of this is to emulate if I receive an instance of NotificationEventArgs with the following values then NewNotification should resemble x.
Edit
In the meantime I will simply use typeof(T).GetConstructor().
You might want to take a look at AutoFixture:
AutoFixture makes it easier for developers to do Test-Driven Development by automating non-relevant Test Fixture Setup, allowing the Test Developer to focus on the essentials of each test case.
After doing some decompilation of Microsoft.Exchange.WebServices and playing bit with reflection, you can do it for example like this:
var fixture = new Fixture();
// retrieve internal FolderEvent(EventType, DateTime) ctor
// using FolderEvent class as NotificationEvent is abstract
var notificationEventCtor = typeof(FolderEvent).GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null,
new Type[] { typeof(EventType), typeof(DateTime) },
null
);
// generate 10 random events with some help of LINQ and AutoFixture
var trashData = Enumerable
.Range(1, 10)
.Select(i => new object[]
{
fixture.CreateAnonymous<EventType>(),
fixture.CreateAnonymous<DateTime>()
})
.Select(p => notificationEventCtor.Invoke(p))
.Cast<NotificationEvent>()
.ToList();
Code above will generate 10 FolderEvents in a list, ready to pass to NotificationEventArgs constructor (which is internal again, so same code applies):
var notificationEventArgsCtor = typeof(NotificationEventArgs).GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null,
new Type[]
{
typeof(StreamingSubscription),
typeof(IEnumerable<NotificationEvent>)
},
null
);
var instance = notificationEventArgsCtor
.Invoke(new object[] { null, trashData });
Take a look at the PrivateObject class (specifically these constructor overloads). It wraps all the reflection work for you and allows you to create objects with non-public constructors, as well as access non-public methods and properties of those objects. You can get the underlying objects via the Target property.

Dependency Injection "nesting" in related methods

We're using DI and Unity to work with different dependencies (generally, database and repository classes, dto to entity mappers, etc)
Right now we're trying to create smaller functions that perform tasks that try to be independend from each other, in order to increase testability and also to avoid methods that have lots of different responsibilities, to avoid coupling
One question that I have is, how should DI be used when we have methods that rely on other inner methods, when the nesting is not trivial. For example, consider the following example (just a concept, not real working code):
public ProcessedOrder ProcessOrders(Order inputOrder)
{
foreach (var line in inputOrder.OrderLines)
{
var someData = LineProcessor(line);
}
}
public SomeData LineProcessor(OrderLine line)
{
/* do some stuff*/
var OtherData = ThingProcessor(null,line.SomeStuff);
var ret = new SomeData();
// assign values, more stuff
return ret;
}
public OtherData ThingProcessor(IDep1 someDependency, SomeStuff stuff)
{
someDependency = someDependency ?? ServiceLocator.Resolve<IDep1>();
var ret = someDependency.DoThings(stuff);
return ret;
}
Ok, so far the example shows that we have 3 functions, that could theoretically be called on their own. there's some injected dependency in the ThingProcessor, and if it's null then it tries to resolve it.
However, this is a somehow simple example, but I see something I don't like so much. For instance, I'm calling ThingProcessor with a null value in the first param. So I can say, ok, I modify the signature of LineProcessor to have it injected, so that he pass it in to the other function that needs it. However, he really doesn't need it, it's not its dependency but the function that he's calling.
So here I don't know what approach is the more correct one, if the one that i'm showing, or if I should pass the correlated dependencies across layers. If I do this last thing, then the outermost function will be a mess, because it'll have a long list of dependencies that it will feed to everyone that's below it.
However, the "null approach" I don't like very much, so I'm pretty sure that something's wrong somewhere, and there's probably a better way to design this.
What's the best approach??? Remember, all functions must be used independently (called on their own), so for example I may call just ThingProcessor at some point, or at another one only LineProcessor.
UPDATE :
public CommonPurposeFunctions(IDep1 dep1, IDep2 dep2 ....)
{
this.Dep1 = dep1;
this.Dep2 = dep2;
[...]
}
public ProcessedOrder ProcessOrders(Order inputOrder)
{
foreach (var line in inputOrder.OrderLines)
{
var someData = LineProcessor(line);
}
}
public SomeData LineProcessor(OrderLine line)
{
/* do some stuff*/
var OtherData = ThingProcessor(line.SomeStuff);
var ret = new SomeData();
var morethings = this.Dep2.DoMoreThings();
// assign values, more stuff
return ret;
}
public OtherData ThingProcessor(SomeStuff stuff)
{
var ret = this.Dep1.DoThings(stuff);
return ret;
}
The approach we use is constructor injection, then we store the dependency in a private member field. The container wires up the dependencies; so the number of classes and constructor parameters doesn't really matter.
This works for services. If the dependencies across calls have meaningful state, you will have to pass them in to each call. But, in that case, I'd question if the methods really need to be public methods in their own classes.
You want to end up with a design that eliminates the service locator and truly injects the dependencies.
Does the null object pattern help?
http://en.wikipedia.org/wiki/Null_Object_pattern

C# String to Object without using Reflection

In C#, is it possible to get an instance of an object based on a string without using Reflection?
For example:
Activator.CreateInstance(Type.GetType(objName));
uses reflection.
Is it possible to replace the classic if\else structure of a factory class with a "string to object" implementation that dosn't use reflection?
I have heard that there is, but I don't see how you would do it without reflection.
There is but it's not a simple solution. Essentially you create a dynamic method and then create a delegate from that and use it.
public static BaseBuilder Create(Type builderType, HttpContextBase httpContext, PathDataDictionary pathData)
{
if (!builderType.IsSubclassOf(baseBuilderType)) return null;
BuilderConstructorDelegate del;
if (builderConstructors.TryGetValue(builderType.FullName, out del))
return del(httpContext, pathData);
DynamicMethod dynamicMethod = new DynamicMethod("CreateBaseBuilderInstance", builderType, constructorMethodArgs, builderType);
ILGenerator ilGenerator = dynamicMethod.GetILGenerator();
ilGenerator.Emit(OpCodes.Ldarg_0);
ilGenerator.Emit(OpCodes.Ldarg_1);
ilGenerator.Emit(OpCodes.Newobj, builderType.GetConstructor(constructorMethodArgs));
ilGenerator.Emit(OpCodes.Ret);
del = (BuilderConstructorDelegate)dynamicMethod.CreateDelegate(typeof(BuilderConstructorDelegate));
builderConstructors.TryAdd(builderType.FullName, del);
return del(httpContext, pathData);
}
Here is some code I use in the Builder for ASP.NET
framework in the BuilderFactory.
If it's not clear in the code, you should know that once you have a delegate then that delete is stored in the dictionary called builderConstructors in the code above. So the next time the factory simply uses the delegate.
In this particular case the class requires two parameters in its constructor. If you're using the default constructor for your classes things are a little simpler.
High Performance Class Factory
Since you're using the dependency-injection tag in your question, Dependency Injection frameworks would typically do this for you. There is always reflection involved, but most of them would have a caching mechanism that prevents any reflection the next time an object is requested. Especially when your type is a concrete type with a default constructor (as you shown in your question) no registration is required. For instance, when using the Simple Service Locator, the request would look like this:
object instance = ServiceLocator.Current.GetInstance(Type.GetType(objName));
When you don't want to use a dependency injection framework, what you can do is generate delegates for the creation of those objects and cache them in a dictionary with objName as key (this is basically what DI frameworks will do). While you can use LCG (as Shiv showed), it has gotten much easier with the new .NET 3.5 Expression trees:
private static Dictionary<string, Func<object>> delegates =
new Dictionary<string, Func<object>>();
public static object CreateObjectByName(string name)
{
if (delegates.ContainsKey(name))
{
return delegates[name]();
}
else
{
Func<object> creator = CreateDelegateFor(Type.GetType(name));
// TODO: Don't forget to make this thread-safe :-)
delegates[name] = creator;
}
}
// .NET Expression tree magic!
private static Func<object> CreateDelegateFor(Type type)
{
var constructor = type.GetConstructors().First();
var newServiceTypeMethod = Expression.Lambda<Func<object>>(
Expression.New(constructor, new Expression[0]),
new ParameterExpression[0]);
return newServiceTypeMethod.Compile();
}
You can use Microsoft.VisualBasic.Interaction.CreateObject, but that only applies to COM objects. (On the plus side, this allows you to create objects on other people's computers.)

Categories