Object creation using Unity Application Block - c#

I'm currently reading up on the Microsoft Unity Application Block in order to use it in one of my personal project. I have read a couple of articles and tutorials about it, but I have a question about it.
In this example about the framework, they use Unity in order to create an object that inherits the IVehicle interface. Those 3 classes that do inherit from it don't have any properties that have to be initialized in the constructor, so everything works well.
Obviously, in my project, this won't always be the case. I'll have some classes that do need property (or field) initialization in the constructor. My question is, how would I achieve that? Or is that something Unity can't do by itself; I would have to create the object using Unity's Resolve() function that would give me an object with uninitialized fields/properties, and then I would have to call the setter one by one on each fields/properties?

Unity supports auto-wiring which allows you to resolve complex object graphs and not just individual objects.
For example, let´s say that you have a class Car implementing ICar that depends on another class IEngine using constructor injection (Car´s constructor requires a parameter of type IEngine).
public interface ICar
{
void Accelerate();
}
public interface IEngine
{
void Accelerate();
}
public class Car: ICar
{
private readonly IEngine _engine;
public Car(IEngine engine)
{
_engine = engine;
}
public void Accelerate()
{
_engine.Accelerate();
}
}
public class Engine: IEngine
{
public Engine()
{
}
public string Message {get; set;}
public void Accelerate()
{
Console.WriteLine("Accelerating." + Message);
}
}
You will then register in Unity how to resolve ICar and IEngine:
var _container = new UnityContainer()
.RegisterType<ICar,Car>()
.RegisterType<IEngine,Engine>(
new InjectionProperty("Message", "Hello world"));
Then when you resolve ICar Unity will be able to provide an instance of Engine to the Car constructor, auto-wiring the dependency that Car has on IEngine. This is also true for any additional dependencies that Car or Engine may have and any properties registered for injection.
var car = _container.Resolve<Car>();
car.Accelerate();
Accelerating.Hello world
This way by resolving an ICar Unity will give you the full object graph needed. You can try the sample in this fiddle
EDIT
You can register a type to be resolved using a lambda method that will be executed at runtime, for example:
public interface IFoo
{
DateTime ResolvedTime {get; set;}
}
public class Foo: IFoo
{
public DateTime ResolvedTime {get; set;}
}
//Can be registered using a lambda as in:
container.RegisterType<IFoo,Foo>(
new InjectionFactory(c => new Foo{ ResolvedTime = DateTime.Now }));
You can get some info on the msdn. I have also updated the fiddle above with this lambda example.

Related

Cross reference generic type C#

I'm trying to create some state machines for the little game I'm making with Unity.
I started with some enums, but as I want to do some multi layer state machines, it's not really a good way.
Looking around the internet, I found some interesting ideas, and I came to this kind of implementation
public interface IStateMachine
{
public BaseState CurrentState { get; set; }
}
public abstract class BaseState
{
private IStateMachine _ctx;
// ... other state stuffs
}
That I'm trying to adapt to use a generic type for the context, like this
public abstract class BaseState<T> where T: IStateMachine
{
private T _ctx;
// ... other state stuffs
}
But that won't compile, saying that I forgot a <T> to BaseState<T> CurrentState in my first interface.
Using the generic type BaseState need 1 type arguments
But how could I tell him that T is the class that implements my interface ?
I tried some stuff, like adding a generic to my interface
public interface IStateMachine<T> where T : IStateMachine<T>
{
public BaseState<T> CurrentState { get; set; }
}
but it simply tell me
The type 'T' cannot be used as type parameter 'T' in the generic type or method 'BaseState'. There is no implicit reference conversion from 'T' to 'IStateMachine'.
I'm probably missing a simple fact about generics, and this question might be a duplicate of this question (state machine, unity, but from 7 years ago).
The problem is probably that you do not declare the type when you make the actual state implementation:
public class StateMachine : IStateMachine
...
public class StateA : BaseState<StateMachine > // need to specify T
public class StateB<T>: BaseState<T> where T : IStateMachine // let caller specify T
But the problem you will run into is that you have to declare all the methods and properties you want to use on the common base type. States need to reference each other, so you will need to use the base type in these references. So you will not really gain anything by using generics.
A workaround for this is to use the Curiously recurring template pattern. i.e.
public abstract class BaseState<T> where T: BaseState<T>{
public T Next {get;}
This essentially gives a way to promise that the entire graph of states will have a common type. This can still allow for methods that do things like traversing the graph, without any need to know the actual type, for example:
public static T NextNext<T>(BaseState<T> start) where T : BaseState<T>{
return start.Next.Next;
}
public class MyState : BaseState<MyState>{
...
}
var myState = new MyState(...);
MyState nn = myState.NextNext(); // Keep the type when traversing the graph
The CurrentState Property inside the IStateMachine probably references to the BaseState which needs a generic type. Either way your structure seem a bit tough because it kind of has a recursive link. IStateMachine needs a BaseState but a BaseState needs a IStateMachine?
I would suggest not trying to let the BaseState know what StateMachine it is attached to.
Another suggestion would be to create another Class "StateMachineContext" which the BaseState has a reference to and this StateMachineContext has a reference to IStateMachine.
Yet another approach would be to have it similiar to the following code:
public interface IStateMachine
{
public BaseState CurrentState { get; set; }
}
public abstract class BaseState
{
// Some functionality that IStateMachine needs access
// to.
}
public abstract class BaseState<T> : BaseState where T : IStateMachine
{
private T _ctx;
// ... other state stuffs
}
Another very simple way to begin a statemachine:
(Instead of providing the Data in the state as a reference you could also pass it as a parameter with whatever function you will call on the state.)
public class Entity
{
public IStateMachine<Entity> StateMachine { get; set; }
}
public interface IStateMachine<T>
{
public BaseState<T> CurrentState { get; set; }
// Some generic state handling functionality
}
public abstract class BaseState<T>
{
private T _ctx;
/*
Some required state handling that will
be called by the entity through the statemachine
*/
}

Unity resolve based on class requesting instance

I'm trying to set up Registrations in Unity, and I'm having trouble getting exactly what I need.
Imagine I have the following definitions:
public interface ISomeInterface { ... }
public interface ISomeDependency { ... }
public class DependencyA : ISomeDependency { ... }
public class DependencyB : ISomeDependency { ... }
public class SomeClassA : ISomeInterface
{
public SomeClassA(ISomeDependency dep){ ... }
}
public class SomeClassB : ISomeInterface
{
public SomeClassB(ISomeDependency dep){ ... }
}
I then register them with Unity as follows:
Container.RegisterType<ISomeDependency, DependencyA>("DependencyA");
Container.RegisterType<ISomeDependency, DependencyB>("DependencyB");
Container.RegisterType<ISomeInterface, SomeClassA>("ClassA");
Container.RegisterType<ISomeInterface, SomeClassB>("ClassB");
I also register a factory that will build an ISomeInterface based off a key.
Container.RegisterType<Func<string, ISomeInterface>(new InjectionFactory(c=>
{
return new Func<string, ISomeInterface>(x=>
{
return c.Resolve<ISomeInterface>(x)
}
}));
(incidentally, if anyone knows a better way of creating keyed factories I'd welcome the tip)
How can I configure Unity such that when Unity builds me an instance of SomeClassA, it will also inject an instance of DependencyA? The same when Unity builds me an instance of SomeClassB, it will inject an instance of DependencyB.
Appreciate your help.
edit: corrected my typo
If you register two concrete types for one interface, Unity will not know which one to resolve to. You'll have to provide more information. One way to do that is to use a parameter override.
// Override the constructor parameter "dep" value
// Use DependencyA instead of other value
var result = container.Resolve<ISomeInterface>(
new ParameterOverride("dep", new DependencyA())
.OnType<SomeClassA>());
But, you've also registered bot SomeClassA and SomeClassB as type of ISomeInteface, so you'll also have to tell Unity which one of those implementations you want when you want an ISomeInterface.

Accessing objects through their interfaces

What does it really mean? I am reading design pattern book. It says
objects are accessed solely through their interfaces, and I am not able to get my head around it, can some body give me an example (Will really appreciate if its in C#)
What do we really achieve by using it?
Thanks
If you have a class called Espson and it implements an interface called IPrinter then you can instantiate the object by it's interface.
IPrinter printer = new Espson();
Epson may have a number of methods that are not part of the IPrinter interface but you may not care. All you may want to do is call a method defined in the IPrinter interface called Print
So then I can pass the class to a method called PrintDocument(IPrinter printer) and the method doesn't care what type of printer it is, it just knows it has a method called Print
The problem is the interface has several meanings. In this case the author is talking that objects must be accessed through public methods (in C# through public properties also) only.
(Of course, inheritors may use protected methods).
Public methods/properties form the public interface of a class. It's not the same interface that described by interface keyword in C#.
That really depends. If the variable is of type "interface", then in that case the object can be accessed by the interface type only.
Let's consider an example - Suppose I have an interface as defined below -
interface IMyInterface
{
string B();
}
and if I implement this interface using a class "MyClass" as shown below -
public class MyClass:IMyInterface
{
public string B()
{
return "In Class";
}
}
public class MyAnotherClass:IMyInterface
{
public string B()
{
return "In Another Class";
}
}
and I create an instance of the class using the interface as shown below
IMyInterface myinst = new MyClass();
then in the above case I can only get access to the Method B() using variable myinst which contains a reference to MyClass type.
Going further, let's say I have a method that takes a parameter of type IMyInterface as shown below -
public class UseOfInterface{
public void InterfaceUse(IMyInterface myPara)
{
myPara.B();
}
}
and I call this method as shown below -
IMyInterface myInst = new MyClass();
IMyInterface myAnotherInst = new MyAnotherClass();
UseOfInterface interfaceUse = new UseOfInterface();
interfaceUse.InterfaceUse(myInst); // returns "In Class"
interfaceUse.InterfaceUse(myAnotherInst); // returns "In Another Class"
Then, as shown above, it is decided at runtime as to which method is called using the Interface variable.
But if I had created a variable of type MyClass which would have contained a reference of type MyClass itself as shown below -
MyClass myinst = new MyClass();
then method B() can be accessed using the MyClass instance. So it depends what type of scenario you are dealing with.
Edit: Why Use Interfaces?
The main reason to use an interface is that it provides a contract to the class for which it is being implemented apart from the multiple inheritance support in C#. Let's can see an example where the contract providing can be helpful.
Suppose you have a class - "Car" in your assembly that you want to expose publicly, the definition of the class is as shown below
namespace CarNameSpace
{
public class Car()
{
public void Drive(IDriver driver)
{
if(driver.Age > 18)
{
driver.Drive();
}
}
}
}
As shown above, anyone who implements the IDriver interface can drive the car, which is defined below,
interface IDriver
{
string Age{get; set;}
string Name {get set;}
string Drive()
}
In turn to drive my car I would be exposing the IDriver interface to the outer world, so anyone who implements my interface can call the Car's Drive method, doesn't matter how he drives the car as shown below
public class PerfectDriver:IDriver
{
public PerfectDriver()
{
Name = "Vikram";
Age = 30;
}
public int Age{get; set;}
public string Name {get; set;}
public string Drive()
{
return "Drive's perfectly";
}
}
The Car class can be used as shown below
PerfectDriver perf = new PerfectDriver
Car myCar = Car();
myCar.Driver(perf);
An interface is a construct that describes the signature of the public members of an object. It contains declarations (declarations only, no implementation) of properties, methods and events that are guaranteed to be present on any object that implements that interface.
Here's a simple interface and a few classes that implement it. The interface "INamed" states simply that objects implementing the interface have a "Name" property that is a string.
public interface INamed{
string Name{get;}
}
public class Person : INamed{
public string Name{get;set;}
}
public class Place : INamed{
public string Name{get;set;}
}
public class Thing : INamed{
public string Name{get;set;}
}
...And a simple method that accepts a parameter of that interface type.
static void PrintName(INamed namedObject){
Console.WriteLine(namedObject.Name);
}
This "PrintName" method can accept a parameter of any type that implements that interface. The advantage of "accessing objects by their interface" is that it infuses your application with a certain flexibility, accessing these interfaces as opposed to their concrete types allows you to operate on these objects without having to know what they really are.
I could, for instance choose to operate on the IDbCommand interface as opposed to a concrete SqlCommand and much of what I write in this manner will be useful when working with a variety of database providers.
The simple idea is that you don't need to know if you're in a car or a boat because you can drive anything with a wheel and pedals.
The interface refers to what the object exposes to users of the object. An object will be an instance of a class which will have its own interface and possibly implement one or more other interfaces.
While languages such as C# allow you to define things called interfaces, those are distinct from the interface referred to in the statement that objects are accessed through their interfaces. In a language such as Scala, for instance, what C# calls an interface is called a trait. Most design patterns do involve the use of defined interfaces, i.e. public interface <interface name>, but again, those are distinct from what is meant in the original statement.
Suppose I define the following class in C#:
public class MyType
{
public void Method1()
{
...
}
private void Method2()
{
...
}
public int Method3()
{
...
}
}
Then the interface through which I interact with the class is the two methods it exposes, void Method1 and int Method2 and the implicit parameterless constructor.
Now, suppose I define the following interfaces and class:
public interface IInterface1
{
void Method1();
}
public interface IInterface2
{
int Method3();
}
public class MyType2 : IInterface1, IInterface2
{
public void Method1()
{
...
}
private void ADifferentMethod()
{
...
}
public int Method3()
{
...
}
}
The interface through which a user interacts with instances of MyType2 is the same as that through which a user interacts with instances of MyType1 (except for the different constructors) because the signatures of the public methods (and other public members) are identical : void Method1 and int Method3.

Unity Static Property Injection

I have two classes, one which sets up the container by registering types and one which contains a static property which I want to inject into. My issue is the property is never set by injection so when I call a method on it, the property is always null.
public class ClassOne
{
public void Method()
{
Container.RegisterType<IClass, ClassImplOne>("ImplOne");
Container.RegisterType<IClass, ClassImplTwo>("ImplTwo");
}
}
public static class ClassTwo
{
[Dependency]
public static IClass SomeProperty { get; set; }
public static void SomeOtherMethod()
{
SomeProperty.AnotherMethod();
}
}
If I remove the Dependency attribute and in ClassOne do a simple
ClassTwo.SomeProperty = Container.Resolve<IClass>("ImplOne");
it works fine, but I want to know if it is possible to do this without explicitly assigning a value to the property (i.e. can the container inject through attributes)?
Edit:
Thanks. I have removed the static declaration from ClassTwo and in ClassOne added RegisterType and Resolve for ClassTwo and also added InjectionProperty:
Container.RegisterType<IClass, ClassImplOne>("ImplOne", new InjectionProperty("SomeProperty"));
but it still does not work :S
Edited after considering comments:
There are a variety of reasons why at times you still want or need to use static classes instead of cascading everything through Unity.
If the static class has a dependency on another class that you would want to be configurable/exchangeable via your Unity configuration I prefer using a factory pattern as described at How to resolve dependency in static class with Unity? or simply assigning a function to resolve the dependency when needed, rather than referencing the Container from within the static class. One advantage being that all your Unity configuration can be in the same place.
In your case it could look like this:
public static class ClassTwo
{
private static IClass _someProperty;
public static Func<IClass> ResolveProperty { private get; set; }
private static IClass SomeProperty
{
get { return _someProperty ?? (_someProperty = ResolveProperty()); }
}
public static void SomeOtherMethod()
{
SomeProperty.AnotherMethod();
}
}
And in your Unity configuration add this:
ClassTwo.ResolveProperty = () => container.Resolve<IClass>();
Unity inject dependencies when the class is resolved through Unity. A static class can not be created, so Unity can not inject dependencies.
Instead of having a Static class, use Unity to resolve a pseudo-singleton class (ContainerControlledLifetimeManager) of ClassTwo. This way Unity injects IClass to ClassTwo when ClassTwo is created (resolved throug Unity container) and, as is configured as singleton, you always have the same instace of ClassTwo in the whole lifecicle of your application.
You must resolve ClassTwo through Unity.
Container.RegisterType<IClass, ClassImplOne>("ImplOne");
Container.RegisterType<IClass, ClassImplTwo>("ImplTwo");
Container.RegisterType<InterfaceImplemetedByClassTwo, ClassTwo>();
//Simple example. Don't forget to use ContainerControlledLifetimeManager for ClassTwo to simulate sigleton.
And when you need ClassTwo:
Container.Resolve<InterfaceImplemetedByClassTwo>
Having the config in ClassTwo:
public class ClassTwo : InterfaceImplemetedByClassTwo
{
[Dependency("ImplOne")] //inject ClassImplOne
public IClass SomeProperty { get; set; }
BUT this is not a great solution, I think your problem is with the phylosophy of DI. You need to cascade dependencies from the top layer classes of your app. Resolve the top layer classes in a explicit way. (Container.Resolve) and dependecies injection cascade down thanks to the magic of Unity. When 2 classes (top layer or not) need to use the same instance of ClassTwo Unity do the dirty work if you configured ClassTwo with ContainerControlledLifetimeManager.
In other words, you don't need static class, you inject the same instance of a class in other classes than need it.

Auto-wiring property injection

I am trying to use property injection for StructureMap in a plug-in style system.
ObjectFactory.Initialize(o => o.Scan(s =>
{
s.AssembliesFromPath("path_to_assemblies");
s.WithDefaultConventions();
});
Here is a sample implementation (purposely did not go deeper in defining T and TU as they are just simple classes)
public interface IBarService
{
void Baz();
}
public class BarService : IBarService
{
public void Baz() { /* implementation */ }
}
public abstract class PluginBase<T, TU> : IPlugin
where T : AClass, new()
where TU : BClass
{
protected PluginBase()
{
//some init code in the constructor
}
}
//Foo is created at run-time via Activator.CreateInstance()
public class FooPlugin : PluginBase<AClass, BClass>
{
[SetterProperty]
public IBarService BarService { get; set; }
public void Fooey()
{
BarService.Baz();
}
}
I want to auto-wire the property dependencies on all of these plug-ins that are created at run-time. I thought I'd start out with property injection and then move things to the constructor if the need arose.
If I do:
var obj = ObjectFactory.GetInstance<IBarService>();
anywhere in an instance of FooPlugin, I get the correct implementation and all is well.
If I do:
this.BarService.Baz();
I get a null reference exception because no instance of IBarService was set.
After I create my plug-in, if I do this:
ObjectFactory.BuildUp(pluginObject).
All is well and FooPlugin has the correct implementation of IBarService.
Is there any way to simply allow me to decorate my plugin properties with [SetterProperty] and have StructureMap automatically inject those when the Plugin is created without having to call ObjectFactory.BuildUp(pluginObject) ?
How are you creating your plugin instance in the cases where it doesn't work? Are you just doing new FooPlugin()?
If you do var plugin = ObjectFactory.GetInstance<PluginBase<AClass, BClass>>();, do you get the plugin with all the correct dependencies resolved?
If you are instantiating the object with "new", the container has no way to know that the instance needs dependencies resolved--it has no knowledge of that instance. Instances that need injected dependencies must be "managed by the container" so to speak.
You'll save yourself a lot of trouble if you just go the opposite route and inject all dependencies in the contstructor(s). This way there is a single place where you need to check if your objects are initialized properly...

Categories