I'm trying to pass our application that was using the old Prism 4.0 to latest Prism 7.1.0.431
I'm almost done, everything compiles. Dependency injection has been updated to use latest Unity. So everything seems back on track as I see injection working somewhat.
Though I still have a problem with Module loading: region manager cannot be resolved. I think I'm missing something in my initialization code but cannot find any relevant documentation on that. Try to get into all Prism.Wpf samples but could find relevant code.
Injecting the region manager within module is probably not a good practice from the code I'm seeing while search an answer to my issue, but bear with me that right now it's a huge application and would want to avoid changing that as much as possible:
Here is the exception error I'm having:
EXCEPTION: Prism.Modularity.ModuleInitializeException: An exception occurred while initializing module 'AdvancedExportModule'.
- The exception message was: Resolution of the dependency failed, type = 'Codex.Modules.AdvancedExport.AdvancedExportModule', name = '(none)'.
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, Prism.Regions.IRegionManager, is an interface and cannot be constructed. Are you missing a type mapping?
Am I missing something initialization code for the RegionManager to be mapped and injected correctly by Unity?
Here are the code sample, I tried to simply the most of it and hopefully it's enough for you to understand what's wrong...
This my App.xaml:
<prism:PrismApplication x:Class="Codex.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/">
<Application.Resources>
<ResourceDictionary Source="Resources/Merged.xaml"/>
</Application.Resources>
</prism:PrismApplication>
And in my Code behind App.xaml.cs
namespace MyNamespace
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Threading;
using Prism.Ioc;
using Prism.Logging;
using Prism.Modularity;
using Prism.Unity;
public partial class App : PrismApplication
{
private static ILoggerFacade Logger { get; set; }
public static void Main()
{
var application = new App();
application.InitializeComponent();
application.Run();
}
protected override void OnStartup(StartupEventArgs startupEventArgs)
{
base.OnStartup(startupEventArgs);
}
protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
{
var modulesFilePaths = new Dictionary<string, string>();
modulesFilePaths.Add("Namespace.Modules.Module1.dll", "Namespace.Modules.AdvancedExport.Module1Module");
var pathToExecutingLibrary = Directory.GetParent(Assembly.GetExecutingAssembly().Location).FullName;
foreach (KeyValuePair<string, string> moduleFilePath in modulesFilePaths)
{
var referenceUri = Path.Combine(pathToExecutingLibrary, moduleFilePath.Key);
var assembly = Assembly.LoadFrom(referenceUri);
var type = assembly.GetType(moduleFilePath.Value);
moduleCatalog.AddModule(
new ModuleInfo(type)
{
ModuleName = type.Name,
Ref = referenceUri,
InitializationMode = InitializationMode.WhenAvailable
});
}
moduleCatalog.Initialize();
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
ConfigureViewModelLocator();
var containerExtension = CreateContainerExtension();
containerRegistry.RegisterInstance(containerExtension);
// These methods have been commented out they are use to register all the types of the application.
//RegisterSettings(containerRegistry);
//RegisterServices(containerRegistry);
//RegisterHandlers(containerRegistry);
//RegisterWrappers(containerRegistry);
containerRegistry.RegisterInstance(Dispatcher.CurrentDispatcher);
}
protected override Window CreateShell()
{
Window mainShell = Container.Resolve<MainShell>();
return mainShell;
}
}
}
You're doing too much and the wrong things in your overrides. Example: RegisterTypes should just register types...
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
// this has already been called by the base class: ConfigureViewModelLocator();
// this has also been called by the base class: var containerExtension = CreateContainerExtension();
// containerRegistry.RegisterInstance(containerExtension);
// These methods have been commented out they are use to register all the types of the application.
//RegisterSettings(containerRegistry);
//RegisterServices(containerRegistry);
//RegisterHandlers(containerRegistry);
//RegisterWrappers(containerRegistry);
containerRegistry.RegisterInstance(Dispatcher.CurrentDispatcher);
}
You should review the source code to get an understanding of how the overrides are supposed to be called. Essentially, they should not call each other, just do their own work.
Related
I am building an aaplication in Xamarin for IOs and sometimes I get these errors.
Microsoft.Practices.ServiceLocation.ActivationException: Activation
error occurred while trying to get instance of type
SurveyNavigationPage, key ""
I can't figure out why am I getting them and can't even trace them to where they are coming from...
I guess I have done something wrong in the Dependancy Injection. I am using Autofac and Service Locator. Below I will demonstrate how I implement the dependancy injection in my project and possibly someone can spot my error.
My code is in the PCL part of the Xamarin project but the error happens iOS Application class for some reason in the UIApplication.Main(args, null, "AppDelegate"); Well at least that is where it crashes if I debug..
My PCL App class instatiates the dependancy injection class like this:
public App()
{
SetUpDIContainer();
InitializeComponent();
MainPage = new NavigationPage(ServiceLocator.Current.GetInstance<MainPage>());
}
private void SetUpDIContainer()
{
var container = new DependencyInjection();
container.Initialize();
}
The Dependancy Injection class looks like this:
public class DependencyInjection
{
private IContainer _container;
public void Initialize()
{
BuildContainer();
SetServiceLocator();
}
private void BuildContainer()
{
var builder = new ContainerBuilder();
builder.RegisterGeneric(typeof(RestRepository<>)).As(typeof(IRest<>));
builder.RegisterType(typeof(PageService)).As(typeof(IPageService));
builder.RegisterType<SurveyController>();
builder.RegisterType<LocationController>();
builder.RegisterType<ClientController>();
builder.RegisterType<RepositoryService>();
builder.RegisterType<MainViewModel>();
builder.RegisterType<SurveyNavigationViewModel>();
builder.RegisterType<EditSurveyViewModel>();
builder.RegisterType<ClientPageViewModel>();
builder.RegisterType<BaseViewModel>();
builder.RegisterType<MainPage>();
builder.RegisterType<SurveyNavigationPage>();
builder.RegisterType<SurveyPage>();
builder.RegisterType<EditSurvey>();
builder.RegisterType<ClientPageView>();
builder.RegisterType<App>();
var http = new HttpClient();
builder.RegisterInstance(http).As<HttpClient>();
_container = builder.Build();
}
private void SetServiceLocator()
{
var csl = new AutofacServiceLocator(_container);
ServiceLocator.SetLocatorProvider(() => csl);
}
}
It is a very strange error as it comes up sometimes and sometimes it doesn't and I can't spot what exactly has to happen in order for it to happen.
I'm working out of the Xamarin Forms for MVVMCross 5 Solution Template and updated the packages to the latest version (5.3.2 for MVVMCross). Doing that changes some namespaces around particularly in the UWP project.
It seems that I need to resolve IMvxViewPresenter as MvxFormsUwpViewPresenter which takes a IMvxWindowsFrame as an argument. In the setup file method of Setup.cs there's a XamlControls.Frame rootFrame passed as an argument but I'm not sure if that's suppose to be cast somehow as IMvxWindowsFrame.
Where can you pull the object that implements IMvxWindowsFrame from or is there another way to turn the rootFrame into an IMvxWindowsFrame legitimately.
public class Setup : MvxFormsWindowsSetup
{
private readonly LaunchActivatedEventArgs _launchActivatedEventArgs;
public Setup(XamlControls.Frame rootFrame, LaunchActivatedEventArgs e) : base(rootFrame, e)
{
_launchActivatedEventArgs = e;
// Mvx.RegisterSingleton<IMvxWindowsFrame>(rootFrame);
}
protected override void InitializeFirstChance()
{
base.InitializeFirstChance();
Mvx.RegisterSingleton<Core.Services.ILocalizeService>(new Services.LocalizeService());
Mvx.RegisterSingleton<ISettings>(CrossSettings.Current);
Mvx.RegisterType<IMvxViewPresenter, MvxFormsUwpViewPresenter>();
}
protected override MvxFormsApplication CreateFormsApplication()
{
return new Core.FormsApp();
}
protected override IMvxApplication CreateApp()
{
return new Core.MvxApp();
}
protected override IMvxTrace CreateDebugTrace()
{
return new Core.DebugTrace();
}
}
public sealed partial class MainPage : WindowsPage
{
public MainPage()
{
this.InitializeComponent();
var start = Mvx.Resolve<IMvxAppStart>();
start.Start();
var presenter = Mvx.Resolve<IMvxViewPresenter>() as MvxFormsUwpViewPresenter;
LoadApplication(presenter.FormsApplication);
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
}
}
EDIT: I've been looking more into the class MvxFormsWindowsSetup in the source code at https://github.com/MvvmCross/MvvmCross/blob/develop/MvvmCross-Forms/MvvmCross.Forms.Uwp/Platform/MvxFormsWindowsSetup.cs. It appears that in the method CreateViewPresenter that the IMvxViewPresenter is registered as a singleton with the MvxWrappedFrame already inside but by default the code does not resolve when calling var presenter = Mvx.Resolve() as MvxFormsUwpViewPresenter; in the windows page. Possible bug? Trying to see if I can resolve it myself.
Looks like it fails to resolve even if I put the code right after when Mvx is suppose to register the type / singleton
protected override IMvxWindowsViewPresenter CreateViewPresenter(IMvxWindowsFrame rootFrame)
{
var presenter = new MvxFormsUwpViewPresenter(rootFrame, FormsApplication);
Mvx.RegisterSingleton<IMvxFormsViewPresenter>(presenter);
var presenter2 = Mvx.GetSingleton<IMvxViewPresenter>() as MvxFormsUwpViewPresenter;
return presenter;
}
When updating to MvvmCross 5.3.2 for UWP, the presenter needs to resolve as IMvxFormsViewPresenter rather than IMvxViewPresenter. Change the interface type and it should load properly.
public MainPage()
{
this.InitializeComponent();
var start = Mvx.Resolve<IMvxAppStart>();
start.Start();
var presenter = Mvx.Resolve<IMvxFormsViewPresenter>() as MvxFormsUwpViewPresenter;
LoadApplication(presenter.FormsApplication);
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
}
I am getting the following error when trying to open GPS settings page if GPS is not enabled (within Xamarin):
Unknown identifier: StartActivity
Unhandled Exception:
Java.Lang.NullPointerException:
Can somebody please guide where am I getting wrong?
This My Interface
namespace MyApp
{
public interface GpsSettings
{
void showGpsSettings();
}
}
This the Implementation
[assembly: Xamarin.Forms.Dependency(typeof(GpsSettingsImplementation))]
namespace MyApp.Droid
{
public class GpsSettingsImplementation : Activity, GpsSettings
{
public GpsSettingsImplementation()
{
}
public void showGpsSettings()
{
var intent = new Intent(Android.Provider.Settings.ActionLocationSourceSettings);
StartActivity(intent);
}
}
}
This is how I call my function on button click
DependencyService.Get<GpsSettings>().showGpsSettings();
An existing Activity instance has a bit of work that goes on behind
the scenes when it's constructed; activities started through the
intent system (all activities) will have a Context reference added to
them when they are instantiated. This context reference is used in the
call-chain of StartActivity.
So, the Java.Lang.NullPointerException seen after invoking
StartActivity on your Test activity instance is because the Context
inside that instance has never been set. By using the new operator to
create an activity instance you've circumvented the normal way
activities are instantiated, leaving your instance in an invalid
state!
ref: https://stackoverflow.com/a/31330999/5145530
The above error can be resolved in the following manner:
[assembly: Xamarin.Forms.Dependency(typeof(GpsSettingsImplementation))]
namespace MyApp.Droid
{
public class GpsSettingsImplementation : Activity, GpsSettings
{
public GpsSettingsImplementation()
{
}
public void showGpsSettings()
{
var intent = new Intent(Android.Provider.Settings.ActionLocationSourceSettings);
intent.SetFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intent);
}
}
}
If I use the Universal Membership Provider and a seperate database, Entity Framework and enable Mini Profiler for EF 4.2. I get error {"There is already an object named 'Applications' in the database."} when I first hit a line checking user credentials in my home view.
If I turn remove MiniProfilerEF.Initialize(); then I stop getting the error.
Any ideas?
Can I stop profiling the defaultconnection?
I have been banging my head against this issue for awhile now. Did some more digging today and was able to get it working. Here is what I did. In MiniProfiler.cs I defined two methods as follows:
public static DbConnection GetConnection()
{
var connectionString = ConfigurationManager.ConnectionStrings["MyModelConnectionString"].ConnectionString;
var entityConnStr = new EntityConnectionStringBuilder(connectionString);
var realConnection = new SqlConnection(entityConnStr.ProviderConnectionString);
return realConnection;
}
public static IMyModelsInterface GetProfiledContext()
{
var connection = new MvcMiniProfiler.Data.EFProfiledDbConnection(GetConnection(), MiniProfiler.Current);
var context = connection.CreateObjectContext<MyModel>();
return context;
}
NOTE: These two methods probably shouldn't be defined in MinProfilerPackage, but this was my first past/hack to get it working.
Then call GetProfiledContext() and use the context returned whenever you want the queries profiled. I injected this profile context into my controller factory using Ninject. My call looks something like this:
public NinjectControllerFactory()
{
ninjectKernel = new StandardKernel();
AddBindings();
}
private void AddBindings()
{
var context = MiniProfilerPackage.GetProfiledContext();
IUnitOfWork uow = new UnitOfWork(context);
ninjectKernel.Bind<IRepository>().To<GenericRepository>().WithConstructorArgument("paramUnitOfWork", uow);
// ... rest of the method
}
NinjectControllerFactory is my controller factory that gets set in Application_Start.
protected void Application_Start()
{
// Add in DI for controller and repo associations
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
// ... rest of the method
}
I would like to experiment with NServiceBus using ASP.NET MVC 3. I've got a solution with NServiceBus installed, plus NinjectMVC3 and NServiceBus.Ninject-CI. Trouble is, I have no idea how to setup NServiceBus stuff in the NinjectMVC3.cs file in App_Start.
Rather annoyingly I'm having trouble finding any examples of how to use NServiceBus.Ninject-CI (I hate it when people don't bother giving examples of how to use their stuff).
Can someone help me get started please?
Load a module like this into the kernel to provide access to the bus
public class NServiceBusModule : NinjectModule
{
public override void Load()
{
this.Bind<IBus>().ToConstant(this.CreateBus()).InSingletonScope();
}
private IBus CreateBus()
{
return NServiceBus.Configure.WithWeb()
.NinjectBuilder(this.Kernel)
... // put NServiceBus config here
.CreateBus()
.Start();
}
}
Read the NServiceBus documentation about how to configure NServiveBus:
http://docs.particular.net/nservicebus/containers/ninject
http://docs.particular.net/samples/web/asp-mvc-application/
Hopefully this will help someone. I had a lot of trouble finding sample code for getting ninject working within NServiceBus.
This code below works for me in place of the more common Castle version:
public class EndpointConfig : IConfigureThisEndpoint, AsA_Publisher, IWantCustomInitialization
{
#region IWantCustomInitialization Members
public void Init()
{
Configure
.With()
.NinjectBuilder(CreateKernel())
.XmlSerializer()
.MsmqTransport();
SetLoggingLibrary.Log4Net(XmlConfigurator.Configure);
}
protected IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Load<MyCustomNinjectModule>();
return kernel;
}
#endregion
}
with the ninject module being the usual format, ie:
public class MyCustomNinjectModule : NinjectModule
{
public override void Load()
{
Bind(typeof(ILogger<>)).To(typeof(Log4NetLogger<>));
...
}
}