Prism - what if multiple modules register the same service - wpf

I am currently playing around with and reading up on Prism. I know that the suggested way is to have some common "services" that are defined as interfaces in the Infrastructure assembly that all modules can reference. Different modules can implement these interfaces and essentially register to provide these services. And other modules can "consume" these services.
I am wondering what happens if two different modules implement the interface and essentially provide the same service. Which service is a consumer going to get when calling the service interface.
Assume I have an INewsFeed and the BlogScraper module implements this service as well as the PrintMagazineScanner module. If I have another module that consumes this service, lets say by displaying the newsfeeds, which of these services is it going to get?

It depends on the IoC container that you use. Generally, if you try to register a service using the same interface twice, it will either throw an exception right away or will let you do so overriding the previous registration or it will throw an exception when you try to request a single instance while there is more than one registered.
For example, if you take MEF, you can export multiple services using the same contract (interface), but when you import those services you have to define a collection property with the ImportMany attribute on it:
[ImportMany]
public IEnumerable<IMyService> MyServices { get; set; }

This has nothing to do with prism. It is more likely a question of the behaviour of your IoC container.

Yes, this is an IoC issue. If you use the ServiceLocator interface then calling GetInstance will usually (including Unity) return the last type that was registered for that service interface. GetAllInstances will return a list of all registered implementations.

Related

Using timers in jboss modules

I am required to create a timer/schedule service in jboss (JEE6). The issue is, it gets deployed as jboss module. I know that following code works if deployed as EJB
#Schedule(hour="*/1", persistent=false)
but it doesnt work if deployed otherwise. Are there any recommendations or standard ways to create and use timers in jboss modules? I want to avoid core-java way of creating TimerTask.
jboss modules are created for sharing code across applications in an efficient way. For more refer here. Now, because modules are not deployed in EJB container; its not possible to use EJB scheduler here. The possible solution or way around for this in our case was to create an EJB which has dependency on these jboss modules whose methods will be invoked by schedulers.
for example,
#Singleton
#Startup
public class NotificationRecorderBean {
#Inject
private MyJbossModule myJbossModule;
#Schedule(hour="*/1", persistent=false)
public void execute() {
LOGGER.debug("Recording notification count");
myJbossModule.process();
}
}

Nancyfx Singleton Per Session

Pardon if this is an obvious question but I don't see a way to get the IOC container in Nancy to provide a Singleton per Session. Obviously, I can check the Session for an item (a model in this case) that I've cached previously but that seems a bit heavy handed given the other niceties of the framework. Hosting in ASP.NET
Per session or per request? There's no way to maintain lifetime of an object for a session (that would be just plain weird), but you can do it per request by overriding ConfigureRequestContainer in the bootstrapper and registering it in there as a singleton like this:
https://github.com/NancyFx/Nancy/blob/master/src/Nancy.Demo.Hosting.Aspnet/DemoBootstrapper.cs#L35

How to get the service context from an entity in RIA Services

I'm using RIA Services for Silverlight and I'm wondering if there's a way to get the service context an entity is attached to from the entity alone (on the client, ie with the RIA-Service domain context and entities!). This would help to implement functionality in them that need some context (the service context itself being one example) without relying on global (static) storage.
You can create many custom DomainContext instances, how you needed. You can cast it to base class (DomainContext) and store it in global storage for second use. In process of second use you should cast it to the custom DaomainContext class again. For example: ((CustomDomainContext)instance).Customers.SubmitChanges();

Why cant WPF's MainWindow be a WCF service?

I have a WPF app that will show youtube videos on my tv via a media center pc. This app will receive commands to PlayVideo(string VideoId), PauseVideo(), etc via a WCF service hosted inside the WPF app.
This is a newbie question, but why can my MainWindow not implement the service contract and then be used as the service using the new ServiceHost() constructor that takes an object singleton in?
When I try I get this exception:
System.InvalidOperationException: Service 'Desktop.MainWindow' has zero application (non-infrastructure) endpoints. This might be because no configuration file was found for your application, or because no service element matching the service name could be found in the configuration file, or because no endpoints were defined in the service element.
My reasoning for doing this is that the simple commands needs to end up at the window anyway, so why not just have the window receive the messages directly instead of indirectly via subscribing to events on the service or having the service have a reference to the MainWindow and call methods on it.
The error, System.InvalidOperationException: Service 'Desktop.MainWindow' has zero application , simply means your app.config (if you have one) does not have the endpoints or the A,B,C's setup correctly (address, binding, contract).
You can host a wcf service in a winform or wpf form, you would only want to do that maybe for a test project in some kind of proof of concept work but never in an application you plan to give to a client or a real user.
If you're new to WPF I strongly recommend reading up on the Model-view-view-Model design pattern. This will allow you to implement the WCF service abstracted away from the UI in your WPF app and will give you a better separation of concerns and responsibilities for the logic in your app.
If you were writing code that others were going to maintain then I'd say...
Why not? Because you're mixing areas of responsibility. The Main Window doesn't need to know anything about WCF, it's job is to present things on screen.
Given that it's your app for your own personal needs, nobody cares what structure you use (just don't ask someone else to maintain it!) :) Having said that, if you want to make it easy for yourself to modify, I'd suggest making an effort to keep the code clean. What you're aiming to do, in my view, doesn't fit that description.
Your mainwindow probably could implement that Service Contract, but I think it's a very bad idea.

Best practice for using Wcf service by silverlight?

How would you structure the code for calling a wcf service in silverlight application?
Using only-once instanciated wcf service-proxy (aka singleton) and using it across the whole SL app?
If so, how did you solve the unsubscribing controls from ws-call-completed event?
or
creating the wcf service-proxy for each ws-call? Where do you close the proxy then?
Here's the application structure I found workable:
Application is split into modules (Prism but can be anything) - module per vertical function.
Every module has its own set of service client classes (generated by slsvcutil)
For every service client partial class I have another generated partial class where for every service method I have a version that returns IObservable.
E.g. if my service client has a method GetAllMyDataAsync() and event GetAllMyDataCompleted the generated method signature will be IObservable<MyDataDto[]> GetMyData() This method will deal with subscribing/unsubscribing to an event, authentication, error handling, and other infrastructure issues.
This way web-service call becomes simply:
new MyServiceClient().GetAllMyData().Subscribe(DoSomethingWithAllMyData)
With this I can easily join data from multiple requests, e.g. (strictly for demonstration purposes, don't try this in real app):
var des = (from d in new MyServiceClient().GetMyDataItem()
from e in new MyServiceClient().GetDataItemEnrichment(d)
select new EnrichedData { Data = d, Enrichment = e});
des.Subscribe(DoSomethingWithEnrichedData);
Once application gets more complex (e.g. data is shared by multiple components, you add messaging that dynamically updates initially retrieved data, etc.) it's helpful to add another element in the stack - Model.
Therefore if I have a service MyDataService I'd have a model class called MyDataServiceModel. It will be registered in the container as singleton and it will be injected into viewmodels that needs it. Thus viewmodels talk to this class when they need data (so rather than calling MyServiceClient.GetAllMyData it would call MyDataServiceModel.GetAllMyData.
This way viewmodels are completely independent of WCF stack (easier to mock, easier to test) Additionally these model classes take care of:
data transformation from/to DTO
enriching and combining data (one model method may join data from more than one request)
handling issues like throttling (e.g. typical scenario, user selected something in a combobox, it caused a request to be sent to a server to retrieve a data for that selection, while that request is being exected user made another change, but for some reason responses came out of order), etc.
combining data pulled on initial load via WCF with data pushed by the service during the session

Resources