Why use Func<> in controller constructor parameters in MVVM applications - wpf

I'm seeing, more and more code like the code below in an MVVM application (WPF and Prism). Controllers have the following code fragments:
public class DispenseOptionController : IDispenseOptionController
{
protected readonly Func<IPharmacyCdmServiceSimpleClient> CdmClient;
protected readonly Func<IPatientServiceSimpleClient> PatientClient;
public DispenseOptionController(Func<IPharmacyCdmServiceSimpleClient> cdmClient, Func<IPatientServiceSimpleClient> patientClient)
{
CdmClient = cdmClient;
PatientClient = patientClient;
}...
I'm trying to understand the role that Func<> plays here. It seems that this delegate is used as parameters to the constructor. Can someone explain to me why anyone would use Func<> in this particular case? And can Func<> be replaced with anything else?

A Func<> is nothing but the Encapsulation of a method that one or more parameter and returns a value of the type specified by the TResult parameter.
You could see some use cases here

Related

Use of Wrapper class for deserialization in callout?

I found the following use of a wrapper class, and was wondering if it is a good practice or whether its just duplication of code for no reason.
//Class:
public class SomeClass{
public Integer someInt;
public String someString;
}
//Callout Class:
public class CalloutClass{
public SomeClass someMethod(){
//...code to do a callout to an api
SomeClass someClassObj = (SomeClass)JSON.Deserialize(APIResponse.getBody(), SomeClass.class);
return someClassObj;
}
}
//Controller:
public class SomeController {
public SomeController(){
someClassObj = calloutClassObj.someMethod();
SomeWrapper wrapperObj = new SomeWrapper();
for(SomeClass iterObj : someClassObj){
wrapperObj.someWrapperInt = iterObj.someInt;
wrapperObj.someWrapperString = iterObj.someString;
}
}
public class someWrapper{
public Integer someWrapperInt{get;set;}
public String someWrapperString{get;set;}
}
}
The wrapper class "someWrapper" could be eliminated if we just use getters and setters ({get;set;}) in "SomeClass."
Could anyone explain if there could be a reason for following this procedure?
Thanks,
James
My assumption (because, code in controller is extra pseudo) is
SomeClass is a business entity, purpose of which is to store/work with business data. By work I mean using it's values to display it (using wrapper in controller), to calculate smth in other entities or build reports... Such kind of object should be as lightweight as possible. You usually iterate through them. You don't need any methods in such kind of objects. Exception is constructor with parameter(s). You might want to have SomeObject__c as parameter or someWrapper.
someWrapper is a entity to display business entity. As for wrapper classes in controllers. Imagine, that when you display entity on edit page and enter a value for someWrapperInt property, you want to update someWrapperString property (or you can just put validation there, for example, checking if it is really Integer). Usually, as for business entity, you don't want such kind of functionality. But when user create or edit it, you may want smth like this.

How Mybatis (iBatis) read my private variable?

I was wondering how Mybatis get the private variable in Java.
For example:
Let's say we have a Java class called Foo:
public class Foo{
private int foolID;
public Foo(int foolID){
this.foolID = foolID;
}
}
And let's create XML mapper for insert.
<insert id="insert" parameterType="Foo">
insert into foo_table (id)
values (#{foolID});
</insert>
Let's say there are FooDAO java class and FooMapper java interface for this insert.
My question is how come foolID is readable even without Getter (Even if there is a getter method for foolID, I never specify what the getter is...). It seems like magic to me, and I know there is no magic for programming... :)
The only way I can think of is reflection.
Thanks for your help in advance.
That's correct, reflection is used to access private fields, but only if accessing private fields is not restricted.
Seams like reflection is used heavily not just to access private fields but to invoke setters getters etc.

UnityContainer can't resolve type

I have a problem with resolving a type which is registered in UnityContainer. In my bootstraper I overrode ConfigureContainer method. Now this method looks like this
protected override void ConfigureContainer()
{
base.ConfigureContainer();
RegisterTypeIfMissing(typeof(IView<ShellViewModel>), typeof(Shell), false);
RegisterTypeIfMissing(typeof(CommandReaderWriter), typeof(CommandReaderWriter), true);
}
Then in function CreateShell (also in bootstraper) I want to get the instance of type CommandReaderWriter so I did this
var raeder = Container.TryResolve<CommandReaderWriter>();
unfortunatelly this returns null value. I also tried
var anotherReader = Container.TryResolve(typeof (CommandReaderWriter));
but it didn't do a trick. However, interesting is the fact that
var isRegistered = Container.IsTypeRegistered(typeof (CommandReaderWriter));
returns true.
so what is approperiate way to register singletone in UnityContainer ?
The two ways I use to register a singleton in Unity are:
_container.RegisterInstance<CommandReaderWriter>(new CommandReaderWriter);
and
_container.RegisterType<CommandReaderWriter,CommandReaderWriter>(new ContainerControlledLifetimeManager());
Both these methods set the Unity LifeTimeManager to be a ContainerControlledLifeTimeManager, which is Unity-speak for a singleton.
If you want to control exactly how the object is constructed use RegisterInstance. The second option is my preferred one because Unity then does all the dependency management for me.

How to use parameterless constructor with ninject di and winforms

I'm working on a WinForm application using ninject for dependency injection. My first problem was that the form being instantiated had a parameter (for DI). I added a parameterless constructor thinking this would help. The problem now is that the code inside the constructor with the parameter gets skipped. Here what it looks like:
On my main form:
private void mnuSettings_Click(object sender, System.EventArgs e)
{
frmSettings objForm = new frmSettings();
objForm.Owner=this;
objForm.Show();
}
In the frmSettings form:
private readonly IApplicationPropertiesInterface _applicationProperties;
public frmSettings()
{
InitializeComponent();
}
public frmSettings(IApplicationPropertiesInterface applicationProperties) : this()
{
_applicationProperties = applicationProperties;
}
When I call _applicationProperties.GetExtractFileSaveLocationDirectory() it blows up because the code to set _applicationProperties was never called.
Im wondering if I have structured this incorrectly, and what the best way to achieve this is. My goal is to call the parameterless constructor, but also set _applicationProperties.
Any assistance would be most grateful.
I'm guessing you might be expecting that having Ninject in the building will mena that new will work differently to normal. It doesn't - you need to be doing a kernel.Resolve<Something> for the DI to kick in. Note that most of these pitfalls are covered in detail on the wiki
Can you edit your answer to include details of what you're doing outside of this form please?
In the meantime, here are some previous questions that overlap significantly:-
What is the best practice for WinForms dialogs with ninject?
How to use Ninject in a Windows Forms application?

Can someone explain the magic going on in Prism's resolve<> method?

I've got a CustomersModule.cs with the following Initialize() method:
public void Initialize()
{
container.RegisterType<ICustomersRepository, CustomersRepository>(new ContainerControlledLifetimeManager());
CustomersPresenter customersPresenter = this.container.Resolve<CustomersPresenter>();
}
The class I resolve from the container looks like this:
class CustomersPresenter
{
private CustomersView view;
private ICustomersRepository customersRespository;
public CustomersPresenter(CustomersView view,
ICustomersRepository customersRepository,
TestWhatever testWhatever)
{
this.view = view;
this.customersRespository = customersRepository;
}
}
The TestWhatever class is just a dummy class I created:
public class TestWhatever
{
public string Title { get; set; }
public TestWhatever()
{
Title = "this is the title";
}
}
Yet the container happily resolves CustomersPresenter even though I never registered it, and also the container somehow finds TestWhatever, instantiates it, and injects it into CustomersPresenter.
I was quite surprised to realize this since I couldn't find anywhere in the Prism documentation which explicitly stated that the container was so automatic.
So this is great, but it what else is the container doing that I don't know about i.e. what else can it do that I don't know about? For example, can I inject classes from other modules and if the modules happen to be loaded the container will inject them, and if not, it will inject a null?
There is nothing magical going on. You are specifying concrete types, so naturally they are resolvable, because if we have the Type object, we can call a constructor on it.
class Fred { };
Fred f1 = new Fred();
Type t = typeof(Fred);
Fred f2 = (Fred)t.GetConstructor(Type.EmptyTypes).Invoke(null);
The last line above is effectively what happens, the type t having been found by using typeof on the type parameter you give to Resolve.
If the type cannot be constructed by new (because it's in some unknown separate codebase) then you wouldn't be able to give it as a type parameter to Resolve.
In the second case, it is constructor injection, but it's still a known concrete constructable type. Via reflection, the Unity framework can get an array of all the Types of the parameters to the constructor. The type TestWhatever is constructable, so there is no ambiguity or difficulty over what to construct.
As to your concern about separate modules (assemblies), if you move TestWhatever to another assembly, that will not change the lines of code you've written; it will just mean that you have to add a reference to the other assembly to get this one to build. And then TestWhatever is still an unambiguously refeferenced constructable type, so it can be constructed by Unity.
In other words, if you can refer to the type in code, you can get a Type object, and so at runtime it will be directly constructable.
Response to comment:
If you delete the class TestWhatever, you will get a compile-time error, because you refer to that type in your code. So it won't be possible to get a runtime by doing that.
The decoupling is still in effect in this arrangement, because you could register a specific instance of TestWhatever, so every call to Resolve<TestWhatever>() will get the same instance, rather than constructing a new one.
The reason this works is because Unity is designed for it. When you Resolve with a concrete type, Unity looks to see if it can resolve from the container. If it cannot, then it just goes and instantiates the type resolving it's dependencies. It's really quite simple.

Resources