Getting lazy instance via kernel (Ninject) - ninject

I am using Ninject in substitution of MEF and I was wondering if it's possible to get lazy instances via standard kernel methods and not via [inject] .
I need this since when building up my application's menu I have to pass all particular view models and then if the user is enabled on that function to add it to the menu
Thanks

Sure thing, you can inject a Lazy<T> and the value will only be instanciated when you access Lazy<T>.Value.
You can also inject a Func<T> and use it to create T whenever you like (with the func, every call creates a new instance).
Of course you can also do IResolutionRoot.Get<Lazy<T>>() or IResolutionRoot.Get<Func<T>>(), but usually that's a sign of bad design (service locator), so use constructor injection when it's feasible.
EDIT: When is the "enabling of the user" happening? Is it a one time thing? What is being displayed before and after?
There might be other/better designs to achieve this but it's hard to say with that little information.

Related

Reusing Java classes with procedural-style code?

There's a solid chance I'm misusing classes here which is why I need your help.
I've started developing with Java EE and one of the problems I am facing is I have a process which I have organised in a class, call it: "SendEmail.java".
Now let's say I have two other classes called "Thunderalert.java" and "FloodAlert.java" which will use all the methods that SendEmails.java has within it.
So I want to know the best way of using the SendEmails methods from each of the other classes.
Should I be creating an instance of SendEmails and accessing each method individually and error checking along the way (what if an exception is thrown?).. It's methods are just procedural code, so it's not really an 'object' as such
Shall I just be using the one method that runs all the other internal ones from within SendMail
Should this SendMail be redesigned as a helper class-type design?
I'm still quite new at Java EE so I'm not sure if there are any options available which I am missing
I think you should have one public method inside SendEmail class.
Btw, I would consider changing its name. I think having method send() when class is called SendEmail is not the best way (not to mention about names like call(), invoke() etc).
This is great article about this problem (The Kingdom of Nouns) in java.
What about something like: new Email(recipient, body).send()?
Or if you want to do it in a service style, I'd call it for example MailService

Instantiation of System.ServiceModel.Description.WsdlContractConversionContext class

For the case of a project requirement, I need to instantiate WsdlContractConversionContext which is not having a constructor for doing so.
Is there any work around to achieve this?
WsdlContractConversionContext is a member of the System.ServiceModel.Description namespace.
Note:
The requirement exactly is that, I am doing an implementation of IWsdlExportExtension.ExportContract and IWsdlImportExtension.ImportContract, and to unit test this implemetation I need the instance of WsdlContractConversionContext.
There are basically two ways to do that: you can either use reflection to call the non-public constructor of the class (making sure you're passing appropriate parameters to it); or you can let WCF create it for you, and use it wherever you need. The WsdlContractConversionContext is passed as one of the parameters to either IWsdlExportExtension.ExportContract or an IWsdlImportExtension.ImportContract, so you'd need to implement one of the two interfaces (exporting is usually easier, since you won't need to fiddle with WSDL-consuming tools), and force the interface to be called (you may need to hit the service metadata endpoint for that).
The post at http://blogs.msdn.com/b/carlosfigueira/archive/2011/10/06/wcf-extensibility-wsdl-export-extension.aspx has an example of an implementation of a WSDL export extension.
Update following edit in the question: many parts of WCF are notoriously hard to be unit tested. If you can't use WCF itself to create the instance, the only alternative you have is to use reflection. To create an instance of the conversion context class you need an instance of a ContractDescription (which you can create for your contract, but isn't easy), and a PortType, which is even harder. I'm afraid that unit testing your implementation of the WSDL export / import extension may not be worth the effort.

Problem with Prism RegionManager and Unity container

I have a main Silverilght project and other modules and I'm using Prism to glue them together along with Unity for Dependency Injection.
I have one of my modules that depends on an IRegionManager which, naturally, gets injected to it by Unity.
The issue I'm running to is that, the Regions property of the RegionManager that I get doesn't contain any regions even though I have declared two of them in my Shell as follows:
regions:RegionManager.RegionName="MainRegion"
I can't figure out the reason of this behavior. I've tried registering a RegionManager as a singleton using
Container.RegisterInstance<IRegionManager>(new RegionManager());
as well as leaving unity handle this. However, I got the same results :(
what I'm trying to achieve is to inject a view into a particular region and activate it, which can't be done using
_regionManager.RegisterViewWithRegion("MainRegion", typeof(MyView));
that's why I need to get hold of the "MainRegion" object itself and manipulate it.
I hope somebody has this figured out. I would be very thankful :)
Edit:
I should mention that the view discovery works just fine, I can RegisterViewWithRegion, but when I check the Regions property of the RegionManager, I find it empty!
while thinking about this problem and the context in which it happened, it striked me that, like most bugs in software, the problem wasn't where I was looking!
My setup was as follows: I started out with the Silverlight Business Application project template. this gave me a MainPage which I used as my Shell, and a couple of views(Home and About). Now, instead of having the regions sit on my Shell, I put them in the Home view, keeping the MainPage as kind of a master page.
My take on this is that Prism sets a RegionManager for the Shell, and passes it around to whoever needs it (using a Dependency Injection Container). This way, when I asked for an IRegionManager in my module, I got the one for my Shell which doesn't really contain any region (hence the empty Regions property).
To solve this, all I had to do was put my regions in their rightfull place: the Shell, and all is working well (for) now.
Update:
Seems like my "take on this" is actually correct :), this is an excerpt from the Prism Documentation: (under Scoped Regions)
Views defining regions with attached properties automatically inherit their parent's RegionManager. Usually, this is the global RegionManager that is registered in the shell window

Alternatives for the singleton pattern?

I have been a web developer for some time now using ASP.NET and C#, I want to try and increase my skills by using best practices.
I have a website. I want to load the settings once off, and just reference it where ever I need it. So I did some research and 50% of the developers seem to be using the singleton pattern to do this. And the other 50% of the developers are ant-singleton. They all hate singletons. They recommend dependency injection.
Why are singletons bad? What is best practice to load websites settings? Should they be loaded only once and referenced where needed? How would I go about doing this with dependency injection (I am new at this)? Are there any samples that someone could recommend for my scenario? And I also would like to see some unit test code for this (for my scenario).
Thanks
Brendan
Generally, I avoid singletons because they make it harder to unit test your application. Singletons are hard to mock up for unit tests precisely because of their nature -- you always get the same one, not one you can configure easily for a unit test. Configuration data -- strongly-typed configuration data, anyway -- is one exception I make, though. Typically configuration data is relatively static anyway and the alternative involves writing a fair amount of code to avoid the static classes the framework provides to access the web.config anyway.
There are a couple of different ways to use it that will still allow you to unit test you application. One way (maybe both ways, if your singleton doesn't lazily read the app.cofnig) is to have a default app.config file in your unit test project providing the defaults required for your tests. You can use reflection to replace any specific values as needed in your unit tests. Typically, I'd configure a private method that allows the private singleton instance to be deleted in test set up if I do make changes for particular tests.
Another way is to not actually use the singleton directly, but create an interface for it that the singleton class implements. You can use hand injection of the interface, defaulting to the singleton instance if the supplied value is null. This allows you to create a mock instance that you can pass to the class under test for your tests, but in your real code use the singleton instance. Essentially, every class that needs it maintains a private reference to the singleton instance and uses it. I like this way a little better, but since the singleton will be created you may still need the default app.config file, unless all of the values are lazily loaded.
public class Foo
{
private IAppConfiguration Configuration { get; set; }
public Foo() : this(null) { }
public Foo( IAppConfiguration config )
{
this.Configuration = config ?? AppConfiguration.Instance;
}
public void Bar()
{
var value = this.Config.SomeMaximum;
...
}
}
There's a good discussion of singleton patterns, and coding examples here... http://en.wikipedia.org/wiki/Singleton_pattern See also here... http://en.wikipedia.org/wiki/Dependency_injection
For some reason, singletons seem to divide programmers into strong pro- and anti- camps. Whatever the merits of the approach, if your colleagues are against it, it's probably best not to use one. If you're on your own, try it and see.
Design Patterns can be amazing things. Unfortunately, the singleton seems to stick out like a sore thumb and in many cases can be considered an anti-pattern (it promotes bad practices). Bizarely, the majority of developers will only know one design pattern, and that is the singleton.
Ideally your settings should be a member variable in a high level location, for example the application object which owns the webpages you are spawning. The pages can then ask the app for the settings, or the application can pass the settings as pages are constructed.
One way to approach this problem, is to flog it off as a DAL problem.
Whatever class / web page, etc. needs to use config settings should declare a dependency on an IConfigSettingsService (factory/repository/whatever-you-like-to-call-them).
private IConfigSettingsService _configSettingsService;
public WebPage(IConfigSettingsService configSettingsService)
{
_configSettingsService = configSettingsService;
}
So your class would get settings like this:
ConfigSettings _configSettings = _configSettingsService.GetTheOnlySettings();
the ConfigSettingsService implementation would have a dependency which is Dal class. How would that Dal populate the ConfigSettings object? Who cares.
Maybe it would populate a ConfigSettings from a database or .config xml file, every time.
Maybe it do that the first time but then populate a static _configSettings for subsequent calls.
Maybe it would get the settings from Redis. If something indicates the settings have changed then the dal, or something external, can update Redis. (This approach will be useful if you have more than one app using the settings.
Whatever it does, your only dependency is a non-singleton service interface. That is very easy to mock. In your tests you can have it return a ConfigSettings with whatever you want in it).
In reality it would more likely be MyPageBase which has the IConfigSettingsService dependency, but it could just as easily be a web service, windows service, MVC somewhatsit, or all of the above.

Create each COM-instance in it's own exe-container

Is there possible to create a COM-instance in it's own, dedicated, host-process?
I guess some background is needed.
We have an end-user client which has it's central logical components inside an singleton-COM object. (Not propper singleton, but it uses global variables internally, so it would fail.) So that there should be only one instance per exe-file. Convenient while making the client.
However, I should now make a "client-simulator" to test the server-side. I therefore which to make 20 instances of the client-component.
If I could make each instance instanciate in its own exe-host, then the singleton-issue would be handled.
Regards
Leif
I have been struggling with this problem for a few days. I finally found a solution that works. My COM object is written using ATL, so my code snippet will be geared toward that, but the technical solution should be clear. It all hinges on how the class objects are registered. The REGCLS_SINGLEUSE flag is the key. I now have separate processes for each object instance.
In the ATL module, override the RegisterClassObjects() function as follows:
HRESULT RegisterClassObjects(DWORD dwClsContext, DWORD dwFlags) throw()
{
return base::RegisterClassObjects(CLSCTX_LOCAL_SERVER, REGCLS_SUSPENDED | REGCLS_SINGLEUSE);
}
From MSDN regarding REGCLS_SINGLEUSE:
REGCLS_SINGLEUSE
After an application is connected to a class object with
CoGetClassObject, the class object is removed from public view so that
no other applications can connect to it. This value is commonly used
for single document interface (SDI) applications. Specifying this
value does not affect the responsibility of the object application to
call CoRevokeClassObject; it must always call CoRevokeClassObject when
it is finished with an object class.
My theory is that because the registration was removed from public view, it causes a new process to be created for the subsequent instantiations.
This other question mentioned a description of how to use DLLHost as a surrogate process:
http://support.microsoft.com/kb/198891
I've never tried this myself, and I don't know off-hand if you can specify flags for the factories (which control if surrogates can be reused for multiple objects), but maybe you can tweak that via DCOMCNFG or OLEVIEW.
My COM days are long gone, but as far as I remember, there's no built-in way to do that.
It might be easier to rewrite your code so it supports multiple instances than to go the one-process-per-instance route with COM, but here's what you could do:
Use thread-local storage for your global variables and write another CoClass, where each instance owns its own thread through which accesses to the class with the global variables are marshaled. This would at least allow you to avoid the performance impact of DCOM.
Write your own out-of-process exe server (similar to windows' DllHost.exe) to host your COM instances. This requires IPC (Inter-Process Communication), so you either have to code something yourself that marshals calls to the external process or use DCOM (presuming your COM object implements IDispatch)