Using UnityEventAggregator only from Prism - unity-container

I am trying to use the Unity event aggregator to do messaging between various parts of an application. Currently, this is the only feature of the Prism framework that I would like to use. I am having some trouble understand basic concepts I think.
My goal is in some places to be able to broadcast a certain event, and then pick that event up in other places. The code that I have found to do that requires access to the Unity Container, which from what I can tell requires configuration in a bootstrapper and the bootstrapper needs to instantiate the window. This seems like a lot of extra hoops to jump through in my situation of just wanting to use the event aggregator.
Can somebody point me in the right direction for the bare minimum code to use the event aggregator and nothing else from Prism?

It turns out all that needs to be done is instantiate an instance of the EventAggregator class that prism provides. No container needed. I did it in a singleton. Here's the code I used:
public class MyEventAggregator
{
private static MyEventAggregator instance = new MyEventAggregator();
public static MyEventAggregator GetInstance()
{
return instance;
}
private EventAggregator _Aggregator;
public EventAggregator Aggregator
{
get
{
return _Aggregator;
}
}
private MyEventAggregator()
{
_Aggregator = new EventAggregator();
}
}

You do not need to initialize your Unity Container in your bootstrapper and the bootstrapper is not required to instantiate the window. You can initialize your Unity container in any class you want. The only problem is to spread the Unity instance over your application to have an accessible reference where it is needed.

Related

Injecting logger into middleware dependency

I have a middleware library I intend on using in multiple projects. The middleware itself looks something like:
public SdkMiddleware(RequestDelegate next, ILogger<SdkMiddleware> logger, ISdk sdk)
{
this.next = next;
this.logger = logger;
this.sdk = agentSdk;
this.sdk.Init();
...
}
Thanks to DI, I can simply inject my logger:
// Would rather this class be internal...
public class Sdk: ISdk
{
private ILogger<Sdk> logger;
public Sdk(ILogger<Sdk> logger)
{
this.logger = logger;
}
public void Init() {
this.logger.Info(...) // Do some logging
}
The downside to this is my class needs to be registered in every ASP.Net project's Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<ISdk, Sdk>();
Is the best/only route? Every time I want to inject a logger into a class, I need to register that class for DI in my composition root?
There is nothing wrong in having the consumer of your library compose the dependencies for this library in the composition root. That's how dependency injection works. You could of course provide some default implementations and a custom extension method that would register those default implementations into the DI and then let the consumer simply call your extension method.
There are a few things that I feel need clarification here:
Dependency injection/inversion of control
To understand what is the benefit of dependency injection(DI) it is better to look at the principle of inversion of control(IoT) that DI implements.
In your case you want SdkMiddleware class to contain a reference to ILogger implementation. The simplest way to do this is for SdkMiddleware class to create an instance of a class that implements ILogger interface. The downside of such approach is that SdkMiddleware needs to know which class implements ILogger interface and how to instantiate it. In other words, SdkMiddleware has control over the creation of ILogger object. The inversion of control happens when the responsibility of knowing which class implements ILogger and how to create an instance of it is taken away from SdkMiddleware to some other class (dependency container in DI) and the instance if it is given to SdkMiddleware to use (through injection in DI). In this case the control over the creation of ILogger object is outside of SdkMiddleware. Since this changes the direction of control, it is called "Inversion of control".
The benefit of this approach is when you will need to provide another implementation of ILogger or change the way you create an instance of that class, you don't need to change SdkMiddleware at all.
Bootstrapping
So now that we clarified why we are using DI, lets take a look at what do we need to actually use it.
The object that creates all instances, controls which object is injected into which and gives away ready to use objects is usually called DI container or IoT container. In asp.net core "IServiceCollection services" is used as such a container. But it still needs to know how to create objects and which implementation to inject for which interface. This is where bootstrapping comes in.
In a bootstrapper class or method you need to specify how objects are built from classes and how classes relate to interfaces. As an example of the former, imagine that you need to pass a connection string for a database from your configuration to a class that creates a db connection. As for the latter, that is exactly what your line "services.AddTransient()" does.
The answer
I am sorry it took so long to get to the actual answer for your question but I wanted to provide some overview first.
Do you need to specify a relation between a class and an interface to inject logger into your class? No. Your class may not even have an interface to begin with and DI container will inject all the dependencies in it by default if you ask for an object of a class instead of an instance of an interface. You can also use or define some convention over configuration solution so that binding of classes and interfaces will happen automatically.
The bottom line is that registration of a class and the actual injection are not connected. But the code you provided is the default way to do this.

Ensuring only a single instance of the RxBleClient

Maybe I'm not understanding the situation correctly, but we're told it's important to have only one instance of the RxBleClient.
Couldn't this be easily accomplished by making it a static member of the Application class?
class MyApp extends Application {
static RxBleClient rxBleClient;
...
}
Also, I'm having a hard time understanding this code (from your Application class):
public static RxBleClient getRxBleClient(Context context) {
RxBleApp application = (RxBleApp) context.getApplicationContext();
return application.rxBleClient;
}
Could you help me understand what it's doing, and why? Why couldn't it simply
return rxBleClient;
It can be accomplished with taking the static member of the class. Tough it is more elegant to pass it through the instance of RxBleApp which make it more testable (if there were any tests for the sample part).
The RxBleClient is referenced in the RxBleApp which is the android Application. The application context can be retrieved from the Context.

Unified way for resolving dependencies / constructor injection

In my point of view it is a little confusing how to resolve dependecies in XLabs.
According to the sample project here is how I register the dependencies (simplified):
1) Platform dependent in MainActivity.cs:
private void SetIoc()
{
var resolverContainer = new SimpleContainer();
resolverContainer.Register<IMediaPicker, MediaPicker>();
Resolver.SetResolver(resolverContainer.GetResolver());
}
2) Platform independent in App.cs:
public App ()
{
DependencyService.Register<ISettings, Settings>();
DependencyService.Register<FooViewModel>();
}
Now, it is rather difficult to resolve the dependencies. The expected way would be resolving by constructor injection, which ends in exceptions:
public FooViewModel(IMediaPicker picker) {} // Exception
public FooViewModel(ISettings settings) {} // Exception
Another, but not optimum way is to resolve by DependencyService / Resover. But here I need to know which I have to use:
public FooViewModel()
{
_picker = Resolver.Resolve<IMediaPicker>();
_settings = DependencyService.Get<ISettings>();
}
This all seems not optimal for me (e.g. for unit testing). Is there a way to unify the whole resolving process, in the best case via constructor?
Theres not reason not to place your implementations in your constructors and pass them down the stack. Define your Interface in your PCL implement it in your Android or IOS specific projects and pass it into the PCL on you APP constructor. It will work fine.
The problem arises though when you start to have more then about 3 interfaces you want to be platform specific. When the constructor of your App starts to get longer then the constructor of your MainPage you might start looking for other options.
DependencyService is a simple low ball container that Xamarin Forms offers you. You can use it for platform specific or within the PCL. It takes simple forms. You register your interface and the implementation you want to use for it and then you can retrieve a new instance of the implementation anywhere in your PCL or platform specific code. It's simple to use.
Register with
DependencyService.Register<IMyInterface,MyClass> ();
Get an instance of MyClass just call
IMyInterface me = DependencyService.Get<IMyInterface> ();
and me will be a brand new baby MyClass.
You could also call it in your Platform specific code.
DependencyService.Register<IMyInterface,MyAndroidVersion> ();
and then in your PCL
IMyInterface me = DependencyService.Get<IMyInterface> ();
would give you MyAndroid version.
XLabs Container works the same way just gives you more options. You don't have to use both in fact I'd recommend against it. Pick one of the three options and use it. If you start with the first two you could eventually outgrow them so XLabs might be the best choice.
Personally I use the SimpleIOC container from MVVMLight. But they are all basically the same thing just with a few different bells and whistles.

asp.net MVC 4 with Data Access Layer using Entity Framework 5?

In my project, i have first created my Data Access Layer using Entity Framework with the following projects in a single solution,
1.Domain Model - Entity Model (.edmx)
2.Services - Business Services, Dtos, Infrastructure(Configurator), Interfaces and Models(Repository)
Now the problem is, i want to connect this data access layer to my MVC project, i do not know how to make the data access layer projects to behave as the models for my mvc project. So can anyone tell me how to connect my data access layer into my controllers and views.. any references is appreciated. Thanks in Advance !
I think what you're asking is what's the best way for controllers to interact with your services and data layer?
One option is to use the mediator pattern, and decouple the services from the controllers.
There's a great implementation for ASP.NET MVC apps: ShortBus, also available on nuget that I've used in a number of projects, and so far it's worked great.
One of the nice things about ShortBus is it's support for dependency injection. In the example below, all the services are created with Ninject, and require the appropriate registration.
The basic idea is you define queries and commands that the controllers will use, and then add handlers to perform the actual work.
public class AddUser : ICommand<User>
{
public string Email { get; set; }
}
and then a handler:
public class AddUserHandler : ICommandHandler<AddUser, User>
{
private IDatabaseService _database;
private IEmailService _email;
public AddUserHandler(IDatabaseService database, IEmailService email)
{
_database = database;
_email = email;
}
public User Handle(AddUser command)
{
bool created = _database.CreateUser(command.Email);
if (created)
{
_email.SendWelcome(command.Email);
}
}
}
Then inside your controller, all you'd do is issue the command:
public class UsersController : Controller
{
private IMediator _mediator;
public UsersController(IMediator mediator)
{
_mediator = mediator;
}
public ActionResult Create(string email)
{
User user = _mediator.Send(new AddUser("foo#bar.com"));
}
}
The things I like about this pattern are:
Controllers don't need to know how to create a user. It issues a command, and the appropriate business logic handles it.
Each handler can require the services it needs. There's no need to pollute the controllers with services only used by a single action.
It's really easy to unit test. I use a mock, and only need to verify that _mediator.Send() was called with the correct parameters. Then to test the handler, I mock IDatabaseService and IEmailService and verify they are called correctly in the 2 cases.
Commands and queries can be reused, and again, the caller never needs to know what's required to handle the request.
As for the Views, I'd recommend ViewModels.
Each View gets it's own ViewModel, which holds whatever is required for showing that particular page. You'd then map your domain objects to their own individual ViewModels, possibly with AutoMapper.
What's nice about ViewModels is you can format the data appropriately (formatting a DateTime maybe), and then your Views don't need any special logic. If later you decide to update the DateTime format, you only need to change it in one place.
Create a (shared) interface to pass to the layer that's between the DAL and MVC, especially if you're unit testing. Use a repository pattern. Check it out here:
http://csharppulse.blogspot.com/2013/09/learning-mvc-part-5repository-pattern.html
This should get you going...

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.

Resources