registering open generic decorators for typed implementations in castle windsor - castle-windsor

While trying to coerce Windsor into wrapping an implementation with a random number of decorators, i've stumbled upon the following:
i have 3 decorators and an implementation all using the same interface.
if you run this code, windsor resolves icommandhandler<stringcommand> as implementation, which, as far as i can tell, is expected behaviour, because the typed implementation can not be registered with the open typed decorators.
However, if you uncomment the line container.Register(Component.For<ICommandHandler<stringCommand>>().ImplementedBy<Decorator1<stringCommand>>());, all three decorators will be used to resolve implementation, which is the desired result (sort of : ).
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer();
container.Register(Component.For(typeof(ICommandHandler<>)).ImplementedBy(typeof(Decorator1<>)));
container.Register(Component.For(typeof(ICommandHandler<>)).ImplementedBy(typeof(Decorator2<>)));
container.Register(Component.For(typeof(ICommandHandler<>)).ImplementedBy(typeof(Decorator3<>)));
//uncomment the line below and watch the magic happen
//container.Register(Component.For<ICommandHandler<stringCommand>>().ImplementedBy<Decorator1<stringCommand>>());
container.Register(Component.For<ICommandHandler<stringCommand>>().ImplementedBy<implementation>());
var stringCommandHandler = container.Resolve<ICommandHandler<stringCommand>>();
var command = new stringCommand();
stringCommandHandler.Handle(command);
Console.WriteLine(command.s);
Console.ReadKey();
}
}
public interface ICommandHandler<T>
{
void Handle(T t);
}
public class stringCommand
{
public string s { get; set; }
}
public abstract class Decorator<T> : ICommandHandler<T>
{
public abstract void Handle(T t);
};
public class Decorator1<T> : Decorator<T>
where T : stringCommand
{
private ICommandHandler<T> _handler;
public Decorator1(ICommandHandler<T> handler)
{
_handler = handler;
}
public override void Handle(T t)
{
t.s += "Decorator1;";
_handler.Handle(t);
}
}
public class Decorator2<T> : Decorator<T>
where T : stringCommand
{
private ICommandHandler<T> _handler;
public Decorator2(ICommandHandler<T> handler)
{
_handler = handler;
}
public override void Handle(T t)
{
t.s += "Decorator2;";
_handler.Handle(t);
}
}
public class Decorator3<T> : Decorator<T>
where T : stringCommand
{
private ICommandHandler<T> _handler;
public Decorator3(ICommandHandler<T> handler)
{
_handler = handler;
}
public override void Handle(T t)
{
t.s += "Decorator3;";
_handler.Handle(t);
}
}
public class implementation : ICommandHandler<stringCommand>
{
public void Handle(stringCommand t)
{
t.s += "implementation;";
}
}
Why exactly is this happening, is this a feature of windsor that i am not aware of? Is there perhaps a different way to achieve the same effect? (without resorting to reflection)

When windsor tries to resolve a component it will first try to resolve the more specific interface. So when you register Component.For it will prefer to resolve this over an open generic type.
If the same interface is registered multiple times, it will use the first one specified.
So if you don't uncommment the line your application will resolve implementation since this is the most specific component.
If you do uncomment the line decorator1 will be resolved and indeed the magic starts. The decorator will now start looking for the first registered component that satisfies it's constructor, in this case that would be decorator1 again (you did notice that your output show decorator1 2 times ?). Which will the resolve the next registered component and so on till it comes to the actual implementation.
So the only thing I can think about is not registering decorator1 as an open generic but as a specific type.
Kind regards,
Marwijn.

Related

Blazor Server - 'Code Behind' pattern: OnInitializedAsync(): no suitable method found to override

I have a Blazor (Server) application which runs perfectly fine, and which adheres to all rules set by Microsoft.CodeAnalysis.FxCopAnalyzers and StyleCop.Analyzers.
A heavily cut-down razor page is as follows:
#inherits OwningComponentBase<MyService>
#inject IModalService ModalService
#inject IJSRuntime JSRuntime
// UI code
#code
{
private readonly CancellationTokenSource TokenSource = new CancellationTokenSource();
ElementReference myElementReferenceName;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await this.myElementReferenceName.FocusAsync(this.JSRuntime);
}
protected override async Task OnInitializedAsync()
{
....
}
public void Dispose()
{
this.TokenSource.Cancel();
}
protected void ShowModalEdit(object someObject)
{
.....
Modal.Show<MyPage>("Edit", parameters);
}
}
Note#1: I used #inherits OwningComponentBase<MyService> based on Daniel Roth's suggestion
Note#2: I am using the Chris Sainty's Modal component component
However, when I try to move all the code from the #code {...} section to a"Code Behind" partial class ("MyPage.razor.cs"), then I run into the following errors....
'MyPage' does not contain a definition for 'Service' and no accessible
extension method 'Service' accepting .....
'MyPage.OnAfterRenderAsync(bool)': no suitable method found to override
'MyPage.OnInitializedAsync()': no suitable method found to override
The type 'MyPage' cannot be used as type parameter 'T' in the generic
type or method 'IModalService.Show(string, ModalParameters,
ModalOptions)'. There is no implicit reference conversion from
'MyPage' to 'Microsoft.AspNetCore.Components.ComponentBase'.
Suggestions?
Your MyPage.razor.cs should inherit from ComponentBase class and your Mypage.razor should inherit from MyPage.razor.cs.
In your "code-behind" class you should use [Inject] attribute for every service you are injecting and make them at least protected properties to be able to use them in your razor components.
Below is an example from one of my testing apps, please note this uses .net-core 3.0, in 3.1 you can use partial classes.
Index.razor
#page "/"
#inherits IndexViewModel
<div class="row">
<div class="col-md">
#if (users == null)
{
<p><em>Hang on while we are getting data...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th class="text-danger">Id</th>
<th class="text-danger">Username</th>
<th class="text-danger">Email</th>
<th class="text-danger">FirstName</th>
<th class="text-danger">LastName</th>
</tr>
</thead>
<tbody>
#foreach (var user in users)
{
<tr>
<td>#user.Id</td>
<td>#user.Username</td>
<td>#user.Email</td>
<td>#user.FirstName</td>
<td>#user.LastName</td>
</tr>
}
</tbody>
</table>
}
</div>
</div>
IndexViewModel.cs
public class IndexViewModel : ComponentBase, IDisposable
{
#region Private Members
private readonly CancellationTokenSource cts = new CancellationTokenSource();
private bool disposedValue = false; // To detect redundant calls
[Inject]
private IToastService ToastService { get; set; }
#endregion
#region Protected Members
protected List<User> users;
[Inject] IUsersService UsersService { get; set; }
protected string ErrorMessage { get; set; }
#endregion
#region Constructor
public IndexViewModel()
{
users = new List<User>();
}
#endregion
#region Public Methods
#endregion
#region Private Methods
protected override async Task OnInitializedAsync()
{
await GetUsers().ConfigureAwait(false);
}
private async Task GetUsers()
{
try
{
await foreach (var user in UsersService.GetAllUsers(cts.Token))
{
users.Add(user);
StateHasChanged();
}
}
catch (OperationCanceledException)
{
ShowErrorMessage($"{ nameof(GetUsers) } was canceled at user's request.", "Canceled");
}
catch (Exception ex)
{
// TODO: Log the exception and filter the exception messages which are displayed to users.
ShowErrorMessage(ex.Message);
}
}
private void ShowErrorMessage(string message, string heading ="")
{
//ErrorMessage = message;
//StateHasChanged();
ToastService.ShowError(message, heading);
}
private void ShowSuccessMessage(string message, string heading = "")
{
ToastService.ShowSuccess(message, heading);
}
protected void Cancel()
{
cts.Cancel();
}
#endregion
#region IDisposable Support
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
cts.Dispose();
}
disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion
}
TLDR
Make sure the namespace in your razor.cs file is correct
Longer explanation
In my case, I got this error when I put the class in the wrong namespace. The page.razor.cs file was in the same directory as the page.razor file and it contained a partial class as accepted by the October 2019 update.
However, even though the files were located in path/to/dir, page.razor.cs had a namespace of path.to.another.dir, which led to this error being thrown. Simply changing the namespace to path.to.dir fixed this error for me!
Came across this error when I used partial class approach and I was trying to scaffold Identity. I changed to base class aprroach it was resolved.
partial class I was using
after adding a component say MyComponent, add a class MyComponent.razor.cs
for injecting services
use
[Inject]
public BuildingServices Services { get; set; }
for base class approach
after adding a component say MyComponent, add a class MyComponent.razor.cs
change the class name and make it inherit from componentBase
MyComponentBase : ComponentBase
and place this at the top of MyComponent.razor
#inherits MyComponentBase
Use protected keyword to make your methods accessible
All the above points are very true. FWIW, and just to add a weird thing that I was finding with this issue; I could not get that error to go away. Everything was declared as it should be. Once you have ruled out all potential coding issues, I have found exiting VS, coming back in, and rebuilding clears it up. It is almost like VS just will not let go of that error.
It took two days of cleaning, rebuilding, ... and it turned out to be a cut and paste error. I copied the razor file from another, similar class, and left this at the top by mistake:
#inject Microsoft.Extensions.Localization.IStringLocalizer<Person> localizer
'Person' was the wrong class, it wasn't defined by any of the include statements. For some strange reason the only error was "OnInitialized() No method found to override."
I found this when upgrading to 6.0. I had to switch from using base classes to using partial classes!

mvvmcross - multiple Init methods in viewmodel with different signature not working

in a main viewmodel where i collect data from another viewmodels, I created in summary two or three public Init methods with different signatures. When i navigate back to the base viewmodel from the other viewmodels with ShowViewModel, I awaited that the right Init method will be executed, but this don't happen. Regarding the greet practical documentation here:
http://slodge.blogspot.ch/2013/03/v3-new-viewmodel-lifecycle.html
This should be work :-/.
I will explain this with some code.
My main view model is e.g.:
public class MainViewModel : MvxViewModel
{
MainViewModel() {}
public class ParameterFirst
{
public string Id { get; set; }
}
public class ParameterSecond
{
public string Id { get; set; }
}
public class ParameterSecond
{
public string Id { get; set; }
}
public class ParameterThird
{
public string Id { get; set; }
}
public void Init(ParameterFirst objFirst)
{
//do something
}
public void Init(ParameterSecond objSecond)
{
//do something
}
public void Init(ParameterThird objThird)
{
//do something
}
}
Then I will navigate from another viewmodel and await that the right Init method will be executed:
public class CollectData_ONE_ViewModel : MvxViewModel
{
CollectData_ONE_ViewModel() {}
public void DidWork()
{
//Hopefully the Init method with argument ParameterFirst should be called
base.ShowViewModel<MainViewModel>(new MainViewModel.ParameterFirst { Id = "11" });
}
}
next here the second viewmodel
public class CollectData_SECOND_ViewModel : MvxViewModel
{
CollectData_SECOND_ViewModel() {}
public void DidWork()
{
//Hopefully the Init method with argument ParameterFirst should be called
base.ShowViewModel<MainViewModel>(new MainViewModel.ParameterSecond { Id = "22" });
}
}
and the third viewmodel
public class CollectData_THIRD_ViewModel : MvxViewModel
{
CollectData_THIRD_ViewModel() {}
public void DidWork()
{
//Hopefully the Init method with argument ParameterFirst should be called
base.ShowViewModel<MainViewModel>(new MainViewModel.ParameterThird { Id = "33" });
}
}
In my code, each time the First Init method is called, I'm really at the end and don't have further ideas :) Did anyone here experienced the same issue? Or do anyone here have another Idea to collect data to the main viewmodel in an elegant way? Thanks a lot in advance for reading :)
The Init mechanism in MvvmCross is deliberately lightweight. If you declare multiple methods, all of them will be called - this is by design. Also if some of the Init parameter objects were to share properties then these would clash - see Custom types in Navigation parameters in v3
As it says in the blog post you reference "generally you will probably only want to use one within your application" - so I'd recommend refactoring to a single navigation parameter object and using your own ViewModel-based logic to decide how your ViewModel should initialise.
If you really do need three Init methods called in three different situations, then you can easily pack and unpack your own parameter objects using a custom method (possibly in a BaseViewModel class) like in https://stackoverflow.com/a/19059938/373321

Using MvvmCross from content providers and activities

I am trying to use MvvmCross v3 in one of my applications which consists of activities, content providers and broadcast receivers. However, I am not quite succeeding.
The application consists of a Core PCL which contains logic, models and viewmodels and a Droid application which contains all MonoDroid-specific stuff.
In Core I have an App:MvxApplication class and in Droid I have a Setup:MvxSetup class which creates an App-instance and initialises stuff.
I can use the IOC parts with content providers, broadcast receivers and non-Mvx-activities without problems. When I now want to add an MvxActivity it falls apart.
When the Mvx Activity launches I get an exception "Cirrious.CrossCore.Exceptions.MvxException: MvxTrace already initialized".
Obviously I am initialising things in the wrong order / wrong place. But, I need a pointer in the right direction.
My App Class
public class App
: MvxApplication
{
public override void Initialize()
{
base.Initialize();
InitialisePlugins();
InitaliseServices();
InitialiseStartNavigation();
}
private void InitaliseServices()
{
CreatableTypes().EndingWith("Service").AsInterfaces().RegisterAsLazySingleton();
}
private void InitialiseStartNavigation()
{
}
private void InitialisePlugins()
{
// initialise any plugins where are required at app startup
// e.g. Cirrious.MvvmCross.Plugins.Visibility.PluginLoader.Instance.EnsureLoaded();
}
}
And my setup class
public class Setup
: MvxAndroidSetup
{
public Setup(Context applicationContext)
: base(applicationContext)
{
}
protected override IMvxApplication CreateApp()
{
return new App();
}
protected override IMvxNavigationSerializer CreateNavigationSerializer()
{
return new MvxJsonNavigationSerializer();
}
public override void LoadPlugins(Cirrious.CrossCore.Plugins.IMvxPluginManager pluginManager)
{
pluginManager.EnsurePluginLoaded<Cirrious.MvvmCross.Plugins.Json.PluginLoader>();
base.LoadPlugins(pluginManager);
}
public void RegisterServices()
{
// I register a bunch of singletons here
}
// The following is called from my content provider's OnCreate()
// Which is the first code that is run
public static void DoSetup(Context applicationContext)
{
var setup = new Setup(applicationContext);
setup.Initialize();
setup.RegisterServices();
}
My Content provider's OnCreate():
public override bool OnCreate()
{
Log.Debug(Tag, "OnCreate");
_context = Context;
Setup.DoSetup(_context);
return true;
}
My MvxActivity:
[Activity(Label = "#string/ApplicationName", MainLauncher = true)]
[IntentFilter(new[] { "Settings" })]
public class SettingsView
: MvxActivity
{
public new SettingsViewModel ViewModel
{
get { return (SettingsViewModel) base.ViewModel; }
set { base.ViewModel = value; }
}
protected override void OnViewModelSet()
{
SetContentView(Resource.Layout.Page_SettingsView);
}
}
Short answer (I'm in an airport on mobile)
all the mvx android views will check the setup singleton has been created - https://github.com/slodge/MvvmCross/blob/vnext/Cirrious/Cirrious.MvvmCross.Droid/Platform/MvxAndroidSetupSingleton.cs (vnext tree - but similar on v3)
so if you are creating a setup, but not setting this singleton, then you will get a second setup created when you first show a view
i suspect you can just get your setup created via the singleton class, but if this isn't flexible enough for your needs, then please log an issue on github
would also love to see some blogging about this - I've not used custom content providers much (at all!)

Create components with circular relationships using Castle Windsor

I'm implementing a finite-state machine, with each class representing a state. Each state knows which other states it can transition to, and this naturally leads to circular relationships. (See the State Design Pattern).
For this simplified example I'm creating two components, where the first component has a reference to the second component, and the second component has a reference to the first.
The problem is that the Windsor framework is correctly setting the references for the first created component, but not setting the references for the second:
Here are the two components:
// DefaultMouseHandler knows about NewLineMouseHandler
public class DefaultMouseHandler : MouseHandler
{
public DefaultMouseHandler()
{
}
public NewLineMouseHandler NewLineMouseHandler
{
get;
set;
}
internal override MouseHandler LeftButtonDown(System.Windows.Input.MouseButtonEventArgs e)
{
return this.NewLineMouseHandler;
}
}
// NewLineMouseHandler knows about DefaultMouseHandler
public class NewLineMouseHandler : MouseHandler
{
public NewLineMouseHandler()
{
}
public DefaultMouseHandler DefaultMouseHandler
{
get;
set;
}
internal override MouseHandler LeftButtonUp(System.Windows.Input.MouseButtonEventArgs e)
{
return this.DefaultMouseHandler;
}
}
I then register the components as so:
_windsorContainer.Register(Classes.FromThisAssembly()
.BasedOn<MouseHandler>()
);
But when I first attempt to create the DefaultMouseHandler:
The DefaultMouseHandler is constructed
The NewLineMouseHandler is constructed
The NewLineMouseHandler is set on the DefaultMouseHandler
But the DefaultMouseHandler is NOT set on the NewLineMouseHandler.
Can this be considered a defect in Castle Windsor?
What's the best way to have the two components referencing each other, without either component being aware of the Windsor container?
I agree with #sll that it might be a sign the design could be improved. On the other hand there are valid reasons for doing what you're doing. If you never resolve NewLineMouseHandler and it's only used as dependency of NewLineMouseHandler, just set the dependency manually:
windsor.Register(Classes.FromThisAssembly()
.BasedOn<MouseHandler>()
.ConfigureFor<NewLineMouseHandler>(
h => h.OnCreate(
c =>
{
var #default = (DefaultMouseHandler) c;
#default.NewLineMouseHandler.DefaultMouseHandler = #default;
}))
);
The solution I've come up with is to use the TypedFactoryFacility.
This allows objects to be created as they are needed, so we don't have the complications of them all being dependent upon one another at initialization time.
public interface IMouseHandlerFactory
{
T CreateHandler<T>() where T : MouseHandler;
}
// In the registration code
_windsorContainer.AddFacility<TypedFactoryFacility>();
_windsorContainer.Register(Classes.FromThisAssembly()
.BasedOn<MouseHandler>(),
Component.For<IMouseHandlerFactory>()
.AsFactory()
);
// The base class
public abstract class MouseHandler
{
// Every mousehandler will create at least one other mouse handler
// This is the factory that they will use for mouse handling creation
// The property will be automatically set by the DI container
public IMouseHandlerFactory MouseHandlerFactory { get; set; }
// Methods the concrete implementations will override
internal virtual MouseHandler LeftButtonDown(MouseButtonEventArgs e) { return this; }
internal virtual MouseHandler LeftButtonUp(MouseButtonEventArgs e) { return this; }
}
// The implementations
public class DefaultMouseHandler : MouseHandler
{
internal override MouseHandler LeftButtonDown(MouseButtonEventArgs e)
{
return this.MouseHandlerFactory.CreateHandler<NewLineMouseHandler>();
}
}
public class NewLineMouseHandler : MouseHandler
{
internal override MouseHandler LeftButtonUp(MouseButtonEventArgs e)
{
return this.MouseHandlerFactory.CreateHandler<DefaultMouseHandler>();
}
}

What is the best way to implement a singleton pattern class in Actionscript 3?

Since AS3 does not allow private constructors, it seems the only way to construct a singleton and guarantee the constructor isn't explicitly created via "new" is to pass a single parameter and check it.
I've heard two recommendations, one is to check the caller and ensure it's the static getInstance(), and the other is to have a private/internal class in the same package namespace.
The private object passed on the constructor seems preferable but it does not look like you can have a private class in the same package. Is this true? And more importantly is it the best way to implement a singleton?
A slight adaptation of enobrev's answer is to have instance as a getter. Some would say this is more elegant. Also, enobrev's answer won't enforce a Singleton if you call the constructor before calling getInstance. This may not be perfect, but I have tested this and it works. (There is definitely another good way to do this in the book "Advanced ActionScrpt3 with Design Patterns" too).
package {
public class Singleton {
private static var _instance:Singleton;
public function Singleton(enforcer:SingletonEnforcer) {
if( !enforcer)
{
throw new Error( "Singleton and can only be accessed through Singleton.getInstance()" );
}
}
public static function get instance():Singleton
{
if(!Singleton._instance)
{
Singleton._instance = new Singleton(new SingletonEnforcer());
}
return Singleton._instance;
}
}
}
class SingletonEnforcer{}
I've been using this for some time, which I believe I originally got from wikipedia of all places.
package {
public final class Singleton {
private static var instance:Singleton = new Singleton();
public function Singleton() {
if( Singleton.instance ) {
throw new Error( "Singleton and can only be accessed through Singleton.getInstance()" );
}
}
public static function getInstance():Singleton {
return Singleton.instance;
}
}
}
Here's an interesting summary of the problem, which leads to a similar solution.
You can get a private class like so:
package some.pack
{
public class Foo
{
public Foo(f : CheckFoo)
{
if (f == null) throw new Exception(...);
}
}
static private inst : Foo;
static public getInstance() : Foo
{
if (inst == null)
inst = new Foo(new CheckFoo());
return inst;
}
}
class CheckFoo
{
}
The pattern which is used by Cairngorm (which may not be the best) is to throw a runtime exception in the constructor if the constructor is being called a second time. For Example:
public class Foo {
private static var instance : Foo;
public Foo() {
if( instance != null ) {
throw new Exception ("Singleton constructor called");
}
instance = this;
}
public static getInstance() : Foo {
if( instance == null ) {
instance = new Foo();
}
return instance;
}
}