PRISM 5, StockTraderRI, NewsController: Injection magic? - unity-container

In the PRISM 5 StockTrader example is a class called NewsController. The only usage in the application is in ArticleNews.xaml.cs:
public partial class ArticleView : UserControl
{
// Note - this import is here so that the controller is created and gets wired to the article and news reader
// view models, which are shared instances
[Import]
#pragma warning disable 169
private INewsController newsController;
#pragma warning restore 169
...
}
I don't understand when and why an instance of NewsController is created.
Thx

The PRISM 5 StockTrader uses MEF as a DI container to resolve dependencies. In this case, the NewsController class is decorated with an Export attribute.
[Export(typeof(INewsController))]
And the ArticleView has a INewsController field decorated with an Import attribute. As soon as the View is created, MEF will inject the dependency.
You might find the following articles useful:
Imports & Exports Attributes
Stock Trader Reference Implementation Using the Prism Library 5.0 for WPF
Managing Dependencies Between Components Using the Prism Library 5.0 for WPF
Hope this helps.
Ezequiel
http://blogs.southworks.net

Related

Dependency injection using PRISM Xamarin Forms doesn't work

I have a problem with dependency injection in my project. I use PRISM framework in my project and I chose Ioc container when create it. Link -> https://github.com/blackpantific/InstagroomEX
In my app.xaml file I associate the class and interface
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterForNavigation();
containerRegistry.RegisterForNavigation<WelcomeView, WelcomeViewModel>();
containerRegistry.RegisterForNavigation<RegistrationView, RegistrationViewModel>();
containerRegistry.RegisterForNavigation<LoginView, LoginViewModel>();
//regestering
containerRegistry.RegisterSingleton<IValidationService, ValidationService>();
}
But my page after initializing() doesn't appear at the screen. This is ViewModel constructor
public RegistrationViewModel(INavigationService navigationService, IUserDataService userDataService,
IValidationService validationService) :
base(navigationService)
{
_userDataService = userDataService;
_validationService = validationService;
}
Something wrong here. When I pass to the RegistrationViewModel() constructor another parameters besides INavigationService navigationService the RegistrationView page doesn't not displayed. What am I doing wrong?
Assuming that WelcomePage is displayed correctly and RegistrationPage is not, I think that Andres Castro is correct: Prism tries to resolve the IUserDataService which is not possible. In the debug output you should see a message that IUserDataService cannot be resolved.
(Note: The following is based on my experiences with Prism and Unity. This might hold for other Dependency Injection frameworks, but it's possible that other frameworks behave differently.)
Prism relies on a Dependency Injection (DI) framework, for example Microsofts Unity application block. What happens when you try to navigate to RegistrationPage is, that Prism (if you are using ViewModelLocator.AutowireViewModel="True") tries to determine the type of the viewmodel (by convention) and asks the underlying DI framework to resolve this type (i.e. create an instance). For each of the required constructors parameters of this type, then again the DI framework tries to resolve them. If the parameters require concrete types it will then try to resolve those. If the parametery require interface (or abstract) types, the DI framework will look at its registrations and if the types have been registered create instances according to this registrations (which in turn might involve resolving other types).
If - however - the parameter requires an interface type which has not been registered, the DI framework does not know how to handle the situation. It coulld of course assume null, but this might lead to errors that might be way harder to track down, hence it will throw an exception (which is swallowed and Logged by Prism).
Now how can you handle the situation?
You'll need to tell the DI framework how to resolve IUserDataInterface. Since RegistrationPageViewModel does not actually use it, you could register null
containerRegistry.RegisterInstance<IValidationService>(null);
Could be irritating later, though. I'd rather remove the dependency of RegistrationPageViewModel to IUserDataService altogether - for now and add it later when it's actually used - or create a mock/stub that implements IUserDataService and is used as long there is no real implementation. This would be registered with the DI framework as you did with IValidationService.

Unable to dispatch custom event in flex mobile application

I am trying to get some code working from an example I came across. most of the functionality works but it is failing when it tries to dispatch a custom event. At the moment the code that is trying to dispatch the event is inside a class that handles amf remoting.
the example has this line in it for the dispatch:
Application.application.dispatchEvent(new
RemoteResultEvent(RemoteResultEvent.USER_UPDATE_COMPLETE,"test"));
but that fails as it does not know what application.application is "Multiple markers at this line:
-Access of undefined property application"
I assume that this is because this was not written for a mobile app. I tried changing the dispatcher to EventDispatcher
EventDispatcher(
new RemoteResultEvent(RemoteResultEvent.USER_UPDATE_COMPLETE, "worked"));
but I then get this error:
TypeError: Error #1034: Type Coercion failed: cannot convert events::RemoteResultEvent#18337731 to flash.events.EventDispatcher.
This is the code in the custom event RemoteResultEvent.as :
package events
{
import flash.events.Event;
public class RemoteResultEvent extends Event {
public static var USER_UPDATE_COMPLETE:String = "UserUpdateComplete";
public var message:String;
public function RemoteResultEvent(eventType:String, message:String) {
super(eventType, false, false);
this.message = message;
}
}
}
I am bumbling around in the dark as I am new to flex and this type of development so I could well be doing something really dumb. Any help would be gratefully received.
Thanks
JaChNo
You seem confused about event dispatching in general.
Events can be dispatched in any Flex class that extends, or has a, EventDispatcher. Most Flex Components, including Application extend EventDispatcher. To dispatch the event, you are on the right track just do:
dispatchEvent(new RemoteResultEvent(RemoteResultEvent.USER_UPDATE_COMPLETE,"test"));
That will dispatch the event from your current class. Not that all Flex UI Components, including those made in MXML can be considered a class.
What you are trying to do is dispatch the event on the main level application; which is a horrible encapsulation breach, but doable. You have to cast it as an Application so you do not get a generic object. Like this:
(Application.application as Application).dispatchEvent(new RemoteResultEvent(RemoteResultEvent.USER_UPDATE_COMPLETE,"test"));
This approach is deprecated since Flex 4; and you use the FlexGlobals.topLevelApplication instead:
(FlexGlobals.topLevelapplication as Application).dispatchEvent(new RemoteResultEvent(RemoteResultEvent.USER_UPDATE_COMPLETE,"test"))
You don't say, but you allude to the fact that you are in a Mobile Project. If so, I would not expect the mx Application class to be available unless you explicitly added the SWC w/ MX Components to your class. You'll have to access the Spark Application, which does not have an Application property. That could be why you are getting the error.
Be sure to import the proper application you want to use:
import spark.components.Application
More info on Spark Application class.

Downgrading from ASP.net 4 MVC 2 to ASP.net 3.5 MVC

I am a bit of beginner with ASP.net MVC, and built most of my original app while following a book.
I am trying to downgrade a project because of server limitations.
I have resolved a number of errors, but now I am stuck on this on:
If I build it builds ok, but when I press play, I get this error:
Compiler Error Message: CS0246: The type or namespace name 'dynamic' could not be found (are you missing a using directive or an assembly reference?)
It occurs on this line:
[System.Runtime.CompilerServices.CompilerGlobalScopeAttribute()]
Line 142: public class views_rooms_index_aspx : System.Web.Mvc.ViewPage, System.Web.SessionState.IRequiresSessionState, System.Web.IHttpHandler {
Line 143:
Line 144: private static bool #__initialized;
Which I believe probably originates from somewhere like this in my View:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
Is System.Web.Mvc.ViewPage something that you can only do in asp.net 4? What do I need to replace this with for ASP.net 3.5?
The dynamic keyword was introduced in .NET 4.0, and will not be available in any version earlier than that.
I believe the default base class for an mvc view in MVC with ASP.NET 3.5 was System.Web.Mvc.ViewPage, without any generic type. If you want to add a strongly typed model (which is recommended whenever you want to pass data from the controller to the view) you should create a view model class, and replace dynamic with the namespace qualified name of your view model.
Example: you want to pass a string name that you got from somewhere in your controller, to the Home/Index view. Do the following:
Create a class HomeIndexViewModel (name doesn't matter, but this is a good one ;) ) in the Models folder of your project, and give it a public string Name {get; set;} property.
In your controller, insantiate this class and set the name. Pass it to the view using the return View(model); overload.
Make your view inherit System.Web.Mvc.ViewPage<YourProject.Models.HomeIndexViewModel>. You can now access the name using Model.Name in the view.
Your Inherits attribute:
Inherits="System.Web.Mvc.ViewPage<dynamic>"
Has the dynamic type as the generic type - change it to the correct ViewModel type.
For example:
Inherits="System.Web.Mvc.ViewPage<ProductViewModel>"
Answers above cover it pretty well.
you might consider using:
http://www.jetbrains.com/resharper/
i have used it to convert my website to web application and it really helps.

Interface IDisposable gone in Flex 4.5?

It seems that Flex 4.5 can not compile my old AIR applications that implement the IDisposable interface. What? Why? And how should memory management be done from now on?
I've searched the Adobe site, various forums and of course googled the net up and down.
Cheers
I can't say I've ever seen a class called IDisposable in the API even after looking at all the docs and searching online. I mean there are tons of interfaces for it, but it's not in the API. I believe you're just missing a file or a reference to a library that had an IDisposable so that you can programically 'destroy' objects and leave it for the GC to collect.
Here's an easy implementation of the pattern:
public interface IDisposable {
function dispose():void;
}
public class MyComponent implements IDisposable {
// Implements dispose method that must be called just before
// releasing a MyComponent object
public function dispose():void {
// Clean up:
// - Remove event listeners
// - Stop timers
// - Set references to null
// - ...
}
...
}
This is a good pattern for follow, but often times isn't needed if each Flex component is encapsulated and uses a good component lifecycle practice.

Purpose of Unity Application Block in Microsoft Enterprise Library?

Can someone explain to me what is the purpose of the Unity Application Block? I tried looking through the documentation but its all very abstract.
What are some practical uses for the Unity block?
Inversion of Control
A quick summation (lot more reading is available this topic, and I highly suggest reading more)...
Microsoft's Unity from the Enterprise Patterns and Practices team is an Inversion of Control container project, or IoC for short. Just like Castle Windsor, StructureMap, etc. This type of development is also referred in lamen's terms as Loosely Coupling your components.
IoC includes a pattern for Dependency Injection of your objects, in which you rely on an external component to wire up the dependencies within your objects.
For example, instead of accessing static managers (which are near impossible to unit test), you create an object that relies on an external dependency to act upon. Let's take a Post service in which you want to access the DB to get a Post.
public class PostService : IPostService
{
private IPostRepository _postRepo;
public PostService(IPostRepository postRepo)
{
_postRepo = postRepo;
}
public IList<Post> GetPosts()
{
return _postRepo.GetAllPosts().ToList();
}
}
This PostService object now has an external dependency on IPostRepository. Notice how no concretes and no static manager classes are used? Instead, you have a loose-coupling of a simple Interface - which gives you the power of wiring up all different kinds of concrete classes that implement IPostRepository.
Microsoft Unity's purpose is to wire up that IPostRepository for you, automatically. So you never have to worry about doing:
// you never have to do this with Unity
IPostRepository repo = new PostRepository();
IPostService service = new PostService(repo); // dependency injection
IList<Post> posts = service.GetPosts();
The above shows where you have to implement two concrete classes, PostRepository() and PostService(). That is tightly-coupling your application to demand/require those exact instances, and leaves it very difficult to unit test.
Instead, you would use Unity in your end point (The controller in MVC, or code behind in ASPX pages):
IUnityContainer ioc = new UnityContainer();
IPostService postService = ioc.Resolve<IPostService>();
IList<Post> posts = postService.GetPosts();
Notice that there are no concretes used in this example (except UnityContainer and Post, obviously)! No concretes of the services, and no repository. That is loosely-coupling at its finest.
Here's the real kicker...
Unity (or any IoC container framework out there!) will inspect IPostService for any dependencies. It will see that it wants (depends) on an instance of IPostRepository. So, Unity will go into it's object map and look for the first object that implements IPostRepository that was registered with the container, and return it (i.e. a SqlPostRepository instance). That is the real power behind IoC frameworks - the power to inspect services and wire up any of the dependencies automatically.
I need to finish my blog post about the comparisons of UNity vs Castle vs StructureMap. I actually prefer Castle Windsor due to its configuration file options, and extensibility points personally.
The Unity Application Block is used for dependency injection. I think the best simple definition for DI is from this question
When you go and get things out of the refrigerator for yourself, you can cause problems. You might leave the door open, you might get something Mommy or Daddy doesn't want you to have. You might even be looking for something we don't even have or which has expired.
What you should be doing is stating a need, "I need something to drink with lunch," and then we will make sure you have something when you sit down to eat.
So for an example,
IUnityContainer container = new UnityContainer();
ILunch lunch = container.Resolve<ILunch>();
Console.WriteLine(lunch.Drink);
This Outputs "Lemonade" because we defined Drink as a Dependency.
public class ILunch {
[Dependency]
public IDrink Drink { get; set; }
}
As far as practicality goes, Dependency Injection is really great when you have Dependencies on other objects and you don't want the developer to have to manually set them. It is that simple. It is also great for mocking. The most used example I can think of that I use is mocking a data layer. Sometimes the database isn't ready so instead of stopping development I have a fake layer that returns fake data. The data object is accessed via DI and can be configured to return objects which access the fake layer or the real layer. In this example I am almost using the DI Container as a configurable factory class. For more on Unity MSDN has some great resources http://msdn.microsoft.com/en-us/library/cc468366.aspx.
Other good DI Frameworks include Spring.NET and Ninject

Resources