AspNetCore RazorEngine will not use FileProviders configured in derived IOptions<RazorViewEngineOptions> - razor

Use Case
A separated template engine that doesn't interfere in any way with normal Razor operation in an AspNetCore (2.X) web app.
Problem
Whilst trying to implement the above, I've created a whole bunch of derived wrapper classes based on RazorViewEngine, RazorViewCompilerProvider, DefaultRazorPageFactoryProvider, DefaultRazorViewEngineFileProviderAccessor and RazorViewEngineOptions in an effort that these can be registered with DI and injected whilst not having side affects in the normal Razor code path. I've succeeded except for one annoying issue, whereby I still need to configure my custom FileProvider (TemplateRepository) within the normal RazorViewEngineOptions rather than my wrapper class.
e.g. In the below code from Startup.cs, even though the file provider is specified in my custom Options object, and that is what is injected into the wrapper classes, the TemplateRepository is not called for a View request unless the second service.Configure is also included (using RazorViewEngineOptions).
services.Configure<TemplateOptions>(options =>
{
options.ViewLocationExpanders.Add(new TemplateNameExpander());
options.ViewLocationFormats.Add("{0}");
options.AreaViewLocationFormats.Add("{0}");
options.FileProviders.Clear();
options.FileProviders.Add(new TemplateRepository(new SqlConnectionFactory(configuration)));
});
services.Configure<RazorViewEngineOptions>(
options =>
{
options.FileProviders.Add(new TemplateRepository(new SqlConnectionFactory(configuration)));
});
This would suggest to me that somewhere in the RazorViewEngine dependency tree the RazorViewEngineOptions is being injected somewhere, but I cannot find it.
Full Source # GitHub

It seems that you have defined your custom RazorViewEngine but you do not tell MVC to use it.
Try to add below codes to add TemplateRazorEngine to MVC view engine.
services.Configure<TemplateOptions>(options =>
{
options.ViewLocationExpanders.Add(new TemplateNameExpander());
options.ViewLocationFormats.Add("{0}");
options.AreaViewLocationFormats.Add("{0}");
options.FileProviders.Clear();
options.FileProviders.Add(new TemplateRepository(new SqlConnectionFactory(configuration)));
});
services.Configure<MvcViewOptions>(options => {
var engine = services.BuildServiceProvider().GetRequiredService<TemplateRazorEngine>();
options.ViewEngines.Add(engine);
});

Late to the party but maybe you will use this in the future. I've also tried a lot of options and in the end I came to the conclusion that child containers would solve my particular issue. Unfortunately the AspNetCore container doesn't support them so I had to implement something quick that might not work in your case. Another option would be to use StructureMap or any other container that supports this functionality.
public class ChildServiceProvider : IServiceProvider, IDisposable
{
private readonly IServiceProvider _child;
private readonly IServiceProvider _parent;
public ChildServiceProvider(IServiceProvider parent, IServiceProvider child)
{
_parent = parent;
_child = child;
}
public ChildServiceProvider(IServiceProvider parent, IServiceCollection services)
{
_parent = parent;
_child = services.BuildServiceProvider();
}
public void Dispose()
{
(_child as IDisposable)?.Dispose();
}
public object GetService(Type serviceType)
{
return _child.GetService(serviceType) ?? _parent.GetService(serviceType);
}
}
And this is how I used it
public class Startup : IStartup
{
public IServiceProvider ChildServiceProvider { get; set; }
IServiceProvider IStartup.ConfigureServices(IServiceCollection services)
{
// Define a wrapper for the RazorViewEngine and it as a singleton
services.AddSingleton<CustomRazorEngine>(serviceProvider =>
{
// get the RazorViewEngine from the childContainer
var razorViewEngine = ChildServiceProvider.GetRequiredService<IRazorViewEngine>();
return new CustomRazorEngine(razorViewEngine);
});
return services.BuildServiceProvider();
}
public void Configure(IApplicationBuilder app)
{
ChildServiceProvider = CreateChildServiceProvider(app);
app.UseMvc();
}
IServiceProvider CreateChildServiceProvider(IApplicationBuilder parentApp)
{
// create the child container from the parentApp and register
// the custom RazorViewEngineOptions that you need for the isolated templating engine
// and whatever custom services that you need
var server = parentApp.ApplicationServices.GetRequiredService<IServer>();
var webHost = WebHost.CreateDefaultBuilder()
.ConfigureServices(services =>
{
services.AddOptions();
services.Configure<RazorViewEngineOptions>(opts =>
{
opts.FileProviders.Clear();
opts.FileProviders.Add(new CustomFileProvider());
});
services.AddMvc();
})
.Build();
return new ChildServiceProvider(parentApp.ApplicationServices, webHost.Services);
}
}
And the custom classes that you would need to implement
public class CustomFileProvider : IFileProvider
{
}
public class CustomRazorEngine
{
private readonly IRazorViewEngine _razorViewEngine;
public CustomRazorEngine(IRazorViewEngine razorViewEngine)
{
_razorViewEngine = razorViewEngine;
}
}
This was tested with dotnet 2.2 but haven't thoroughly tested it to be 100% that there are no performance issues or other hidden ones.
Also would be curious to know if you found another solution :)

Related

How to load to container MassTransit EndPoint in AbstractFacility

I have a PersistenceFacility class .
This class inhereted "AbstractFacility" as "Castle.MicroKernel.Facilities".
I wonder load and install into container: IWindsorContainer.
public class PersistenceFacility: AbstractFacility
{
protected override void Init()
{
ServiceIoC.Container.Register(Component.For<IBusControl>().LifeStyle.Singleton.UsingFactoryMethod(k =>
{
var busControl = Bus.Factory.CreateUsingRabbitMq(config =>
{
config.Host(new Uri("blabla"), host =>
{
host.Username("guest");
host.Password("guest");
});
config.ReceiveEndpoint("", endpoint =>
{
endpoint.EnableMessageScope();
// Above method works but it is deprecated, instead below method should be used to get Consumer from container.
//endPoint.Consumer<YourConsumer>(container.Kernel);
});
});
return busControl;
}).LifeStyle.Singleton.Named("XXXMassTransitRMQ"));
}
// installer class
public class PersistenceInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container?.AddFacility<PersistenceFacility>();
}
}
//UOW Class
public class UnitOfWork
{
internal static IBusControl MassTransitRmqControl => ServiceIoC.Container?.Resolve<IBusControl>("XXXMassTransitRMQ");
}
First, I would consider moving to use the new container support for Windsor, as outlined in the documentation.
You can see how MassTransit registers components with Windsor by looking at the configuration.
I'm not sure an abstract facility is the way to go, given the approach taken by the links referenced above.

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!)

Update UI thread from portable class library

I have an MVVM Cross application running on Windows Phone 8 which I recently ported across to using Portable Class Libraries.
The view models are within the portable class library and one of them exposes a property which enables and disables a PerformanceProgressBar from the Silverlight for WP toolkit through data binding.
When the user presses a button a RelayCommand kicks off a background process which sets the property to true which should enable the progress bar and does the background processing.
Before I ported it to a PCL I was able to invoke the change from the UI thread to ensure the progress bar got enabled, but the Dispatcher object isn't available in a PCL. How can I work around this?
Thanks
Dan
All the MvvmCross platforms require that UI-actions get marshalled back on to the UI Thread/Apartment - but each platform does this differently....
To work around this, MvvmCross provides a cross-platform way to do this - using an IMvxViewDispatcherProvider injected object.
For example, on WindowsPhone IMvxViewDispatcherProvider is provided ultimately by MvxMainThreadDispatcher in https://github.com/slodge/MvvmCross/blob/vnext/Cirrious/Cirrious.MvvmCross.WindowsPhone/Views/MvxMainThreadDispatcher.cs
This implements the InvokeOnMainThread using:
private bool InvokeOrBeginInvoke(Action action)
{
if (_uiDispatcher.CheckAccess())
action();
else
_uiDispatcher.BeginInvoke(action);
return true;
}
For code in ViewModels:
your ViewModel inherits from MvxViewModel
the MvxViewModel inherits from an MvxApplicationObject
the MvxApplicationObject inherits from an MvxNotifyPropertyChanged
the MvxNotifyPropertyChanged object inherits from an MvxMainThreadDispatchingObject
MvxMainThreadDispatchingObject is https://github.com/slodge/MvvmCross/blob/vnext/Cirrious/Cirrious.MvvmCross/ViewModels/MvxMainThreadDispatchingObject.cs
public abstract class MvxMainThreadDispatchingObject
: IMvxServiceConsumer<IMvxViewDispatcherProvider>
{
protected IMvxViewDispatcher ViewDispatcher
{
get { return this.GetService().Dispatcher; }
}
protected void InvokeOnMainThread(Action action)
{
if (ViewDispatcher != null)
ViewDispatcher.RequestMainThreadAction(action);
}
}
So... your ViewModel can just call InvokeOnMainThread(() => DoStuff());
One further point to note is that MvvmCross automatically does UI thread conversions for property updates which are signalled in a MvxViewModel (or indeed in any MvxNotifyPropertyChanged object) through the RaisePropertyChanged() methods - see:
protected void RaisePropertyChanged(string whichProperty)
{
// check for subscription before going multithreaded
if (PropertyChanged == null)
return;
InvokeOnMainThread(
() =>
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(whichProperty));
});
}
in https://github.com/slodge/MvvmCross/blob/vnext/Cirrious/Cirrious.MvvmCross/ViewModels/MvxNotifyPropertyChanged.cs
This automatic marshalling of RaisePropertyChanged() calls works well for most situations, but can be a bit inefficient if you Raise a lot of changed properties from a background thread - it can lead to a lot of thread context switching. It's not something you need to be aware of in most of your code - but if you ever do find it is a problem, then it can help to change code like:
MyProperty1 = newValue1;
MyProperty2 = newValue2;
// ...
MyProperty10 = newValue10;
to:
InvokeOnMainThread(() => {
MyProperty1 = newValue1;
MyProperty2 = newValue2;
// ...
MyProperty10 = newValue10;
});
If you ever use ObservableCollection, then please note that MvvmCross does not do any thread marshalling for the INotifyPropertyChanged or INotifyCollectionChanged events fired by these classes - so it's up to you as a developer to marshall these changes.
The reason: ObservableCollection exists in the MS and Mono code bases - so there is no easy way that MvvmCross can change these existing implementations.
If you don't have access to the Dispatcher, you can just pass a delegate of the BeginInvoke method to your class:
public class YourViewModel
{
public YourViewModel(Action<Action> beginInvoke)
{
this.BeginInvoke = beginInvoke;
}
protected Action<Action> BeginInvoke { get; private set; }
private void SomeMethod()
{
this.BeginInvoke(() => DoSomething());
}
}
Then to instanciate it (from a class that has access to the dispatcher):
var dispatcherDelegate = action => Dispatcher.BeginInvoke(action);
var viewModel = new YourViewModel(dispatcherDelegate);
Or you can also create a wrapper around your dispatcher.
First, define a IDispatcher interface in your portable class library:
public interface IDispatcher
{
void BeginInvoke(Action action);
}
Then, in the project who has access to the dispatcher, implement the interface:
public class DispatcherWrapper : IDispatcher
{
public DispatcherWrapper(Dispatcher dispatcher)
{
this.Dispatcher = dispatcher;
}
protected Dispatcher Dispatcher { get; private set; }
public void BeginInvoke(Action action)
{
this.Dispatcher.BeginInvoke(action);
}
}
Then you can just pass this object as a IDispatcher instance to your portable class library.
Another option that could be easier is to store a reference to SynchronizationContext.Current in your class's constructor. Then, later on, you can use _context.Post(() => ...) to invoke on the context -- which is the UI thread in WPF/WinRT/SL.
class MyViewModel
{
private readonly SynchronizationContext _context;
public MyViewModel()
{
_context = SynchronizationContext.Current.
}
private void MyCallbackOnAnotherThread()
{
_context.Post(() => UpdateTheUi());
}
}

Castle Windsor and WCF Web Api Message Handlers

I'm trying to use Castle Windsor to create my message handlers because just using ...
MessageHandlers.Add(typeof(MyHandler));
... doesn't allow me to use constructor injection of other services, for example a logger
So, I've create an installer which registers all my handlers (of which there is currently one!)
public class MessageHandlerInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(
AllTypes
.FromThisAssembly()
.Where(t => t.IsSubclassOf(typeof (DelegatingHandler)))
.Configure(c => c.LifeStyle.Custom(InstallerContext.LifestyleManager))
);
}
}
This works fine, when I run it through the debugger I can see the extra component registration in the container.
But when I try to set up the message handler factory for WCF Web Api it doesn't appear to work. (I have breakpoints in the SendAsync method which never gets hit)
public class MyApiConfiguration : WebApiConfiguration
{
public MyApiConfiguration(IWindsorContainer container)
{
EnableTestClient = true;
IncludeExceptionDetail = true;
CreateInstance = ((serviceType, context, request) => container.Resolve(serviceType));
ErrorHandlers = (handlers, endpoint, description) => handlers.Add(container.Resolve<GlobalErrorHandler>());
MessageHandlerFactory = () => container.ResolveAll<DelegatingHandler>();
}
}
So, I'm obviously missing something. I just don't know what it is. Can anyone enlighten me?
EDIT (extra config code, as requested)
public void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
AddServiceRoutes(routes);
}
private static void AddServiceRoutes(RouteCollection routes)
{
Container = WindsorContainerBootStrap.CreateContainerAndInstallComponents<PerThreadLifestyleManager>();
var config = new EtailApiConfiguration(Container);
routes.MapServiceRoute<CustomersApi>("customer", config);
routes.MapServiceRoute<ConsumerApi>("consumer", config);
routes.MapServiceRoute<PricePlansApi>("priceplans", config);
}
EDIT 2 (The Solution)
I had a constructor to my Handler like so ...
public MyHandler(DelegatingHandler innerChannel, ILogger logger)
: base(innerChannel)
{
_logger = logger;
}
... that wasn't getting called despite the changing the init code to use a lambda ...
MessageHandlerFactory = () => container.ResolveAll<DelegatingHandler>();
... so I added another constructor which just takes an ILogger and all is well. I figured that my container didn't know what a Delegating Handler was and that the MessageHandlerFactory must be dealing with that somehow.
You need to use the lambda for ctor injection, that is why it is there. BTW, you are missing a ()
How are you registering your routes, are you passing in the configuration object?

Castle, sharing a transient component between a decorator and a decorated component

Consider the following example:
public interface ITask
{
void Execute();
}
public class LoggingTaskRunner : ITask
{
private readonly ITask _taskToDecorate;
private readonly MessageBuffer _messageBuffer;
public LoggingTaskRunner(ITask taskToDecorate, MessageBuffer messageBuffer)
{
_taskToDecorate = taskToDecorate;
_messageBuffer = messageBuffer;
}
public void Execute()
{
_taskToDecorate.Execute();
Log(_messageBuffer);
}
private void Log(MessageBuffer messageBuffer)
{}
}
public class TaskRunner : ITask
{
public TaskRunner(MessageBuffer messageBuffer)
{
}
public void Execute()
{
}
}
public class MessageBuffer
{
}
public class Configuration
{
public void Configure()
{
IWindsorContainer container = null;
container.Register(
Component.For<MessageBuffer>()
.LifeStyle.Transient);
container.Register(
Component.For<ITask>()
.ImplementedBy<LoggingTaskRunner>()
.ServiceOverrides(ServiceOverride.ForKey("taskToDecorate").Eq("task.to.decorate")));
container.Register(
Component.For<ITask>()
.ImplementedBy<TaskRunner>()
.Named("task.to.decorate"));
}
}
How can I make Windsor instantiate the "shared" transient component so that both "Decorator" and "Decorated" gets the same instance?
Edit: since the design is being critiqued I am posting something closer to what is being done in the app. Maybe someone can suggest a better solution (if sharing the transient resource between a logger and the true task is considered a bad design)
Edit2: Castle3 has added support for this (http://docs.castleproject.org/Windsor.Whats-New-In-Windsor-3.ashx) by introducing the "Bound" lifestyle
'Transient' explicitly means 'non-shared', so what you are asking is conceptually the wrong thing to do. The correct solution is to register Shared as a Singleton instead of Transient:
container.Register(Component.For<Shared>());
(Singleton is the default lifetime in Windsor.)
However, I suspect that behind the stated question lies a much more complex problem. I'm guessing that you need Shared to be Transient because you need it with this lifestyle for a lot of other cases, but exactly when it comes to the relationship between Decorator and Decorated you need to share them.
I still think this sounds like a Design Smell, but there are at least two ways you can achieve this result.
The first option involves prematurely resolving Shared and explicitly supply the resolved instance to the configuration of the two IFoo registrations:
container.Register(Component.For<Shared>().LifeStyle.Transient);
var r = container.Resolve<Shared>();
container.Register(Component
.For<IFoo>()
.ImplementedBy<Decorator>()
.DependsOn(new { resource = r }));
container.Register(Component
.For<IFoo>()
.ImplementedBy<Decorated>()
.DependsOn(new { resource = r }));
The second option is to make a specialized, named registration for Shared that is used only by the IFoo registrations:
container.Register(Component.For<Shared>().LifeStyle.Transient);
container.Register(Component.For<Shared>().Named("shared"));
container.Register(Component
.For<IFoo>()
.ImplementedBy<Decorator>()
.ServiceOverrides(new { resource = "shared" }));
container.Register(Component
.For<IFoo>()
.ImplementedBy<Decorated>()
.ServiceOverrides(new { resource = "shared" }));