WPF Prism Why RegisterType? (with container) - wpf

From my understanding, prism's unity container can resolve types event if they have not been registered, does this make _container.RegisterType kinda useless ?
Thanks!

If I am understanding your question correctly, what you are seeing is that Unity can (try to) make instances of classes directly, which is different from resolving types. It is perfectly reasonable to ask Unity to create a class "directly", however, in order to leverage "Inversion of Control", you would normally ask a container to resolve an interface, where you have mapped an interface to a class via RegisterType. This way you can map different implementations of classes to interfaces, without having to change your code, that is "Inversion of Control" and "Interfaced-based Programming" at work.
This process involves you asking to resolve an interface, followed by Prism finding what is bound to the interface i.e. resolution, and then making an instance for you i.e. factory capabilities. The factory capabilities of Unity will ensure that any other dependencies are resolved that are required to make an instance of the resolved class e.g. using dependency injection on class constructor parameters. This whole process is recursive until all dependencies are resolved.
For Example
If you ask for an IFoo and it is bound Foo, Unity will try and make an instance of Foo. If Foo has a constructor which takes an IBar, Unity will try and resolve IBar and create an instance of this to use in the constructor for IFoo.
So in the following code:
We can resolve IFoo as described above.
We can make an instance of class Bar directly, as it has no dependencies.
We can make an instance of class Foo directly, as it has a dependency on IFoo, but we have registered it.
We cannot make an instance of Woo directly as there is no registration for IYay.
//Types
public interface IBar{}
public class Bar : IBar {}
public interface IFoo{}
public class Foo : IFoo{ public Foo(IBar bar) {} }
public interface IYay{}
public class Woo { Woo(IYay yay){} }
//Registrations
container.RegisterType<IFoo, Foo>();
container.RegisterType<IBar, Bar>();
//Resolve IFoo
IFoo foo = container.Resolve<IFoo>();
//Create Bar directly
Bar bar = container.Resolve<Bar>();
//Create Foo directly
Foo foo = container.Resolve<Foo>();
//Create Woo directly - won't work as IYay is not registered!
Yay yay = container.Reolve<Yay>();
In the example above RegisterType is used to map a concrete implementation to an interface. It is at this point that we can map any implementation we want and this will ripple throughout our program as long as the container is always used to resolve types.
For example, if we change what IBar is mapped to, then any time IFoo is resolved it will be created with that different implementation of IBar. This gives us a substantial way of altering a program's behaviour by just changing a single line of code i.e. RegisterType.

Related

Using getApplicationContext() vs. referencing to custom Application class in Android

I've been researching ways to store global settings for my Android application and so far the best way seems to extend the Application class and store the shared data inside it, as described here. I've discovered that instead of using (CustomApplicationClass)getApplicationContext().getSomething() i can do the same thing by referencing directly to the static method inside the class like this: CustomApplicationClass.getSomething() and both ways work just fine.
Here's a piece from CustomApplicationClass:
public class CustomApplicationClass extends Application {
private static boolean something;
#Override
public void onCreate() {
[...]
}
public static boolean isSomething() {
return something;
}
public static void setSomething(boolean something) {
this.something = something;
}
}
Now, if i want to retrieve value of "something" variable somewhere in my code, say, from my application Activity, is there a difference between:
boolean var1 = ((CustomApplicationClass)getApplicationContext()).isSomething();
and
boolean var1 = CustomApplicationClass.isSomething();
? When running the application, both work fine. Is the second way safe to use, or is it inadvisable?
I've been researching ways to store global settings for my Android application and so far the best way seems to extend the Application class and store the shared data inside it, as described here.
Except that you're not doing that.
I've discovered that instead of using (CustomApplicationClass)getApplicationContext().getSomething() i can do the same thing by referencing directly to the static method inside the class like this: CustomApplicationClass.getSomething() and both ways work just fine.
Of course. You could just as easily had CustomApplicationClass extend Object, then executed CustomApplicationClass.getSomething(). You are gaining nothing by your current approach versus just using an ordinary singleton pattern in Java, and you are losing flexibility, as an application can only have one custom subclass of Application.
Is the second way safe to use, or is it inadvisable?
The first way is pointless, since your data member and methods are static.
Either:
Make your stuff in CustomApplicationClass not be static, and then use getApplicationContext().
Refactor CustomApplicationClass to not extend Application, and then use the static data member and/or accessor methods, or switch more formally to the Java singleton pattern.
Personally, I would go with option #2.
If you check the api of android.app.Application (http://developer.android.com/reference/android/app/Application.html) then you will find on Class Overview as following:
Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's tag, which will cause that class to be instantiated for you when the process for your application/package is created.
There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.

Have a module dependent Injection for State in PRISM WPF application

hi we have a PRISM WPF MVP application, we would like to have a state to share data between the views in the same module. Since PRISM by default doesnt have a state, was wondering if there is any way i could implement this. Presently i have injected a State with Dictionary as back-store, but the problem is its Global i.e available across the modules. i would really like to scope this injection being module specific.
I believe unity allows registering different classes to the same interface based on name, not sure if the only choice i have is to leverage that for my scenario.
Any help would be great! Thanks!
-ioWint
I would agree, scoping Unity's type registration with the ModuleName would be a place to start.
Inject a local(module level) state object into all the views that want to have share state. If the interface that defines the state object is local to your module then other modules won't be able to reference the state object because they can't reference the interface.
So: If Module A has 3 views that take an object implementing IStatefulContainer (also declared in Module A) and IStatefulContainer is registered with Unity using RegisterInstance rather than just RegisterType you'll have a singleton that is scoped to the module.
My preference would be to have a "State" service that managed state. This could allow you to add more functionality here if you needed it and is a more "Prismy" approach.
EDIT
If you're using this state object across modules then you can do the following:
1)Put the interface in an assembly that will be referenced by any module that wants to use it.
Assembly A
public interface IBlah
{
string Add(string stateKey, string stateValue);
}
Assembly B (referencing Assembly A)
public class Module:IModule
{
private IUnityContainer _container;
public Module(IUnityContainer container)
{
_container=container;
}
public void Initialize()
{
IBlah blah1=new BlahContainer();
IBlah blah2=new BlahContainer();
_container.RegisterInstance<IBlah>(blah1,"BlahContainer1");
_container.RegisterInstance<IBlah>(blah2,"BlahContainer2");
}
}
Module C(references assembly A)
_container.Resolve<IBlah>("BlahContainer1");
_container.Resolve<IBlah>("BlahContainer2");
Basically, we define the interface in an assembly we're happy to share between modules. Some projects have "Infrastructure" or Common assemblies that contain service interfaces that are used by other modules - this would fit well here.
We then have our module reference the assembly with the contract in it.
At the moment I'm relying on "magic strings" here but there are lots of ways around this.
Hope this is a little more clear.
thanks for your updated solution. I was trying to avoid a name based Unity registration, which would force my Presenter in knowing the Modules State registration Key.
I was reading stackoverflow posts on Unity and found the discussion over here Is it possible to override parameter values when using Method Injection with Unity? .
After couple of hours of trial and errors, i ended up achieving the desired functionality.
What i have done:
I have a BaseClass for my Modules -> BaseModule:IModule i have a State Property in it which conforms to my IStateService defined in the Infrastructure.Interface. I Instantiate this State property in the BaseModule() constructor.
Note: to go with this approach i have to make my Presenter's have a public IStateService State; property..
At the time of registering the Presenter in the module, i am specifying
<UnityContainer>.RegisterType<MyPresenter, new InjectionProperty("State", State).
Am overriding a public property in Presenter which has name "State" with the State instance value defined in the Module.
this way i am able to get the Modules State as the State for each of the View's presenter.
Thanks guys for directing me towards a solution.
-ioWint

WPF, Prism, MEF. Register region adapter within a module?

Is it possible to register a region adapter within a module?
I have a ContentControl in my Shell.xaml set to region "MainRegion" that currently gets populated with a module containing the AvalonDock control. I currently have the AvalonDock region adapter in my Shell app but would like to place it in the module and register itself. I want to keep this program flexible so that if we decide to use something other than AvalonDock, I can easily use another module without having to modify my Shell assembly (removing the avalondock region adapter).
I imagine something like this is possible. Has anyone done this before?
In bootstrapper right now is:
protected override RegionAdapterMappings ConfigureRegionAdapterMappings()
{
RegionAdapterMappings mappings = base.ConfigureRegionAdapterMappings();
var regionBehaviorFactory = Container.GetExportedValue<IRegionBehaviorFactory>();
var regionManager = Container.GetExportedValue<IRegionManager>();
mappings.RegisterMapping(typeof(Pane), new AvalonRegionAdapter(regionBehaviorFactory, regionManager));
return mappings;
}
This is what I would like to perform in the Module instead of the Shell bootstrapper.
Answer is here from codeplex http://compositewpf.codeplex.com/discussions/250892
The scenario you're describing is
possible. Although custom region
adapters are intended to be registered
in the RegionAdapterMappings in the
Bootstrapper's
ConfigureRegionAdapterMappings method,
it is possible to register a custom
region adapter from within a module.
You could, for example, obtain a
reference to the RegionAdapterMappings
in your Module class by using
constructor injection, and call the
RegisterMapping method there. This is
possible since there is a class named
MefRegionAdapterMappings, which
exports the RegionAdapterMappings as a
shared export. Note that you should be
aware of the timing issues that may
arise due to this. You should be
careful to register the custom mapping
before attempting to create a region
which uses that adapter.

How to create WPF/Silverlight module utilizing prism but also that can be embedded in non-prism applicationss

I want to have create a WPF or Silverlight module which cannot only be utilised by Shell's bootstrapper, but also can be embedded in non-PRISM applications.
In short is there a way PRISM module can be intialised from module itself rather than initialsing from Shell?
Ulimate goal is to have WPF/Silverlight PRISM module, which can be initialsed by non-PRISM applications.
There is no barrier to this.
The IModule interface has a single, parameterless void method: Initialize().
A non-prism application can initialize the module by calling that method. That's it.
If the other application has a different plugin system, with a different interface, your module can implement that interface as well, and the body of whatever initialization method that interface uses can simply call Initialize(), or vice versa.
For example:
public interface IMyPluginModule
{
void StartModule();
}
public class MyModule : IModule, IMyPluginModule
{
public void Initialize()
{
// actual initialization code here
}
public void StartModule()
{
Initialize();
}
}
It's a little more complicated than it appears at first glance, but it is doable. I don't know if you are using Prism 4 yet, but if so, Microsoft actually provides guidance for this scenario:
http://msdn.microsoft.com/en-us/library/ff921109(v=PandP.40).aspx
There is a bit of project manipulation you need to do to get two projects running side-by-side. There is a sample included with Prism v4 called "MultiTargeting" if you need to see a working sample.
Your question regarding to allowing a module to be initialized by itself, rather than having the orchestrating Shell / Bootstrapper is the wrong approach, however. Essentially what you would have would be two shells... one WPF and one Silverlight. Take a look at the samples and see what you think.
Hope this helps.

Ninject for winforms - does my architecture make this useless?

I'm trying out Ninject with a winforms app (basically a sketch, I'm using it sort of like a kata, but nothing so rigorous or specific) in .net 4.
To create the main form, I'm doing something like:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
[...]
IKernel kernel = BuildKernel();
Application.Run(kernel.Get<frmMain>());
}
static IKernel BuildKernel()
{
var modules = new INinjectModule[]
{
[..modules]
};
return new StandardKernel(modules);
}
}
Fine. This creates a main form and displays it nicely, passing the appropriate interface implementations to the injected constructor.
Now what? My application is an MDI and will have several child windows for manipulating the application model. I don't have a reference to the kernel anymore, so how am I supposed to Get() these forms? The obvious answer is 'pass the kernel to the form' I suppose, but that's a horribly messy strategy and I'm sure that doesn't fit into the philosophy of DI.
I will point out here that the documentation for Ninject 2 sucks. Everything I can find repeats the basic examples, without really explaining how DI using Ninject makes anything easier. The standard of example given isn't complicated enough to make the trouble of coding and creating modules and bindings worthwhile.
edit #1:
Having studied the links kindly provided by Sam Holder, I'm trying out the 'composition root' approach. My architecture now forces all the Forms it uses to derive from a CompositedForm with constructor semantics thus:
[Inject]
public CompositingForm(ICompositionRoot CompositionRoot)
{
InitializeComponent();
this.CompositionRoot = CompositionRoot;
}
public readonly ICompositionRoot CompositionRoot;
public CompositingForm() : this(new DummyCompositionRoot()) { }
The second constructor is for the benefit of the Forms Designer, which is stupid and can't understand the form markup unless you provide an empty constructor. Now, every form created using IKernel.Get<AForm>() will (should) have a composition root injected into it.
So, as I am a slow learner - now the question is really 'What should go in this composition root'?
can't you pass a factory for creating the child forms to the forms constructor, and the form uses this to get them, then ninject will wire up the factory dependency when the form is created using the get?
I think you should configure everything in the application root using the DI container and after that the container shouldn't be needed, but I've not really used DI containers in anger, and not NInject at all, so am going on what I've read...
This answer may help
Note: I do not know much about Ninject but i worked with Spring.net that is much more complicated. The principles behind sould be something similar.
Sam Holder answer is excellent if you have several objects of one (injected) type to create (for example CustomerOrderItem).
If you just want to wire your mainform i would sugest that your mdi-frmMain constructor gets parameters for every childwindow it should contain and let Ninject create and insert the childwindows. This way there is no need to Reference NInject outside "class Program
". This is called Constructor-Injection.
Alternatively you can add a method to the form that adds a page to you mdi (MethodInjection).
static void Main()
{
[...]
IKernel kernel = BuildKernel();
var main = kernel.Get<frmMain>();
main.AddClientForm(kernel.Get<CustomerForm>()) ;
main.AddClientForm(kernel.Get<InvoiceForm>()) ;
Application.Run(main);
}
Thanks to João Almeida and Kellabyte I have found a method that is more or less satisfactory:
Define a custom Attribute which exposes whatever business rules you care about;
Define an implementation of IInjectionHeuristic which recognises this attribute;
Use a ViewModelLocator to load modules into the ninject kernel.

Resources