I register an instance with Unity like this:
ContentSlideControlsEntity contentSlideControlsEntity = new ContentSlideControlsEntity(new Queue<uint>());
container.RegisterInstance(typeof(ContentSlideControlsEntity), "contentSlideControlsEntity", contentSlideControlsEntity);
And then I simply want to reslove it:
ContentSlideControlsEntity contentSlideControlsEntity2 = container.Resolve<ContentSlideControlsEntity>();
but I get the following runtime error:
Microsoft.Practices.Unity.ResolutionFailedException: 'Resolution of
the dependency failed, type =
"MSDataLayer.Entities.ContentSlideControlsEntity", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type Queue`1 has
multiple constructors of length 1. Unable to disambiguate.
At the time of the exception, the container was:
Resolving MSDataLayer.Entities.ContentSlideControlsEntity,(none)
Resolving parameter "slideIDQueue" of constructor
MSDataLayer.Entities.ContentSlideControlsEntity(System.Collections.Generic.Queue`1[[System.UInt32,
mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089]] slideIDQueue)
Resolving System.Collections.Generic.Queue`1[System.UInt32],(none)
You registered your instance as a named registration, but you are resolving the unnamed registration (which doesn't exist).
container.RegisterInstance(typeof(ContentSlideControlsEntity), "contentSlideControlsEntity", contentSlideControlsEntity);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
You have 2 options:
1) Don't register it as a named registraion
container.RegisterInstance(typeof(ContentSlideControlsEntity), contentSlideControlsEntity);
2) Resolve it with a name
container.Resolve<ContentSlideControlsEntity>("contentSlideControlsEntity");
Related
In my IContainer I am trying to register my DBContext. And this approach works:
builder.Register(c =>
{
var opt = new DbContextOptionsBuilder<ProjectsDbContext>();
opt.UseSqlServer("Server=(localdb)\\MSSQLLocalDB;Database=Portfolio_Strona;Trusted_Connection=True;MultipleActiveResultSets=true");
return new ProjectsDbContext(opt.Options);
}).AsSelf().InstancePerLifetimeScope();
And now I wanted to replace connection string with this:
string connString= ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
builder.Register(c =>
{
var opt = new DbContextOptionsBuilder<ProjectsDbContext>();
opt.UseSqlServer(connString);
return new ProjectsDbContext(opt.Options);
}).AsSelf().InstancePerLifetimeScope();
And I am getting exception:
Autofac.Core.DependencyResolutionException: 'An exception was thrown
while activating
CV_Creator.Desktop.ViewModels.ProjectLoaderViewModel.'
2 inner exceptions:
DependencyResolutionException: An exception was thrown while invoking
the constructor 'Void .ctor(CV_Creator.DAL.IProjectRepository,
CV_Creator.Services.IProjectCollectionDisplayService,
CV_Creator.Services.IWindowManager)' on type 'ProjectLoaderViewModel'.
and
SqlException: A network-related or instance-specific error occurred
while establishing a connection to SQL Server. The server was not
found or was not accessible. Verify that the instance name is correct
and that SQL Server is configured to allow remote connections.
(provider: SQL Network Interfaces, error: 50 - Local Database Runtime
error occurred. Specified LocalDB instance name is invalid. )
How can I register or resolve ConfigurationManager, that Autofac can see it?
Things I already tryed:
This
System.Configuration.ConfigurationBuilder does not contain definition
for SetBasePath
Microsoft.Extensions.Configuration.ConfigurationBuilder does not
contain definition for SetBasePath
This
Autofac.Core.DependencyResolutionException: 'An exception was thrown
while activating CV_Creator.Desktop.ViewModels.ProjectLoaderViewModel
-> CV_Creator.DAL.ProjectRepository -> λ:CV_Creator.DAL.ProjectsDbContext.' Inner exception:
ComponentNotRegisteredException: The requested service
'Microsoft.Extensions.Configuration.IConfiguration' has not been
registered. To avoid this exception, either register a component to
provide the service, check for service registration using
IsRegistered(), or use the ResolveOptional() method to resolve an
optional dependency.
Is there any way to resolve ConfigurationManager with Autofac IoC container?
UPDATED
New approach tried, in IoC Container:
builder.RegisterType<ProjectsDbContext>().InstancePerLifetimeScope();
and in DbContext:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(ConfigurationManager.AppSettings["connectionString"]);
}
I receive exception:
Autofac.Core.DependencyResolutionException: 'An exception was thrown
while activating CV_Creator.Desktop.ViewModels.ProjectLoaderViewModel
-> CV_Creator.DAL.ProjectRepository -> CV_Creator.DAL.ProjectsDbContext.' DependencyResolutionException: None
of the constructors found with
'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type
'CV_Creator.DAL.ProjectsDbContext' can be invoked with the available
services and parameters: Cannot resolve parameter
'Microsoft.EntityFrameworkCore.DbContextOptions1[CV_Creator.DAL.ProjectsDbContext] options' of constructor 'Void .ctor(Microsoft.EntityFrameworkCore.DbContextOptions1[CV_Creator.DAL.ProjectsDbContext])'.
The project is a copy of Unity doc but it raise an error that I cant underestand
The error is:
Unhandled Exception:
Unity.Exceptions.ResolutionFailedException: Resolution of the
dependency failed, type = 'System.Object', name = 'MainPage'.
Exception occurred while: Calling constructor
SecondPrims.Views.MainPage(). Exception is: ResolutionFailedException
- Resolution of the dependency failed, type = 'SecondPrims.ViewModels.MainPageViewModel', name = '(none)'. Exception
occurred while: while resolving. Exception is:
InvalidOperationException - The current type, ITextToSpeech, is an
interface and cannot be constructed. Are you missing a type mapping?
----------------------------------------------- At the time of the exception, the container was: Resolving
SecondPrims.ViewModels.MainPageViewModel,(none) Resolving parameter
'textToSpeech' of constructor
SecondPrims.ViewModels.MainPageViewModel(ITextToSpeech textToSpeech)
Resolving ITextToSpeech,(none)
----------------------------------------------- At the time of the exception, the container was: Resolving
SecondPrims.Views.MainPage,MainPage (mapped from System.Object,
MainPage)
Resolving SecondPrims.Views.MainPage,MainPage
Calling constructor SecondPrims.Views.MainPage() occurred
Project file:
http://www.mediafire.com/file/fs656jowkiy2bd9/SecondPrims.zip
The answer is because of registering the ITextToSpeech Interface in each platform.
https://stackoverflow.com/a/50493741/478162
Prism 7 changed this behavior as it is actually an anti-pattern to
rely on a secondary container. You simply need to register your
TextToSpeech service in the IPlatformInitializer like:
public class iOSInitializer : IPlatformInitializer
{
public void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.Register<ITextToSpeech, TextToSpeech_iOS>();
}
}
Are you adding your dependencies correctly ?
containerRegistry.RegisterForNavigation<MainPage>();
containerRegistry.Register<ITextToSpeech, TextToSpeech>();
Using the latest RxUI v8 preview and Splat 2.0, in a UWP project referencing a .Net Standard 2.0 library, I can't register my view and viewmodel unless they reside in the same assembly.
I have:
Locator.CurrentMutable.RegisterLazySingleton(() => new HomeView(), typeof(IViewFor<HomeViewModel>));
But Splat gives an error:
DefaultViewLocator: Failed to find type named 'RxUI.UWP.Core.Views.HomeView, RxUI.UWP.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
DefaultViewLocator: Failed to resolve service for type 'ReactiveUI.IViewFor`1[[RxUI.UWP.Core.ViewModels.HomeViewModel, RxUI.UWP.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'.
DefaultViewLocator: Failed to find type named 'ReactiveUI.IRoutableView, ReactiveUI, Version=8.0.0.0, Culture=neutral, PublicKeyToken=null'.
DefaultViewLocator: Failed to resolve service for type 'ReactiveUI.IViewFor`1[[ReactiveUI.IRoutableViewModel, ReactiveUI, Version=8.0.0.0, Culture=neutral, PublicKeyToken=null]]'.
DefaultViewLocator: Failed to resolve view for view model type 'ReactiveUI.IRoutableViewModel'.
DefaultViewLocator: Failed to find type named 'RxUI.UWP.Core.Views.HomeView, RxUI.UWP.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
So it's looking for the HomeView in the "Core" assembly, but it resides in the UWP project. Here's the structure...
I experienced the same issue with a similar environment as your. The issue resided in the DefaultViewLocator, since the view type is being renamed and resolved incorrectly to the viewmodel's assembly and namespace.
See lines 133-134 for how the view type name is determined:
var viewModelTypeName = viewModelType.AssemblyQualifiedName;
var proposedViewTypeName = this.ViewModelToViewFunc(viewModelTypeName);
Note: ViewModelToViewFunc is only a String.Replace that replaces "ViewModel" to "View" (see constructor).
To resolve this issue, my workaround was to create my own IViewLocator implementation, something like:
public class MyViewLocator : IViewLocator {
public MyViewModelLocator(Assembly viewAssembly, string viewNameSpace)
...
private IViewFor AttemptViewResolutionFor(Type viewModelType, string contract)
{
// proposed view type is now based on provided namespace + classname as modified by ViewModelToViewFunc
if (viewModelType == null) return null;
var viewModelTypeName = viewModelType.Name;
var proposedViewTypeName = _viewNamespace + "." + this.ViewModelToViewFunc(viewModelTypeName);
...
private IViewFor AttemptViewResolution(string viewTypeName, string contract)
{
try
{
// resolve view type in the assembly of the view, and not assembly of the viewmodel
var viewType = _viewAssembly.GetType(viewTypeName); // instead of Reflection.ReallyFindType(viewTypeName, throwOnFailure: false);
...
}
Finally, your custom viewlocator implementaiton must be registered with splat so that it overwrites DefaultViewLocator implementation:
Locator.CurrentMutable.RegisterConstant<IViewLocator>(new MyViewLocator(typeof(SplashView).Namespace, typeof(SplashView).Assembly));
I have an asp.net WebAPI app. I'm returning files to the client in the Request.CreateResponse(,) second parameter as type Dictionary<string, List<System.Net.Http.StreamContent>>, where List<System.Net.Http.StreamContent>> contains all the files.
I'm deserializing the files at the client using the following:
var someContent = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, List<System.Net.Http.StreamContent>>>(result.Content.ReadAsStringAsync().Result);
This code throws the exception:
An unhandled exception of type
'Newtonsoft.Json.JsonSerializationException' occurred in
Newstonsoft.Json.dll.
Additional information: Unable to find a construction to use for type
System.Net.Http.StreamContent. A class should either have default
constructor, one constructor with arguments or a constructor marked
with the JsonConstructor attribute. Path 'myFiles[0].Headers'
Is there a different way to return actual files?
http://pastebin.com/QaCCM2Zv
I have a config file in the above link, every time i try to access the section 'InventoryFactory' using this code:
var config = (ObjectFactoryConfiguration)ConfigurationManager.GetSection("InventoryFactory");
it returns an error:
An exception of type 'System.Configuration.ConfigurationErrorsException' occurred in System.Configuration.dll but was not handled in user code
Additional information: An error occurred creating the configuration section handler for InventoryFactory: Could not load type 'WDG.ObjectFactory.ObjectFactoryConfiguration' from assembly 'System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
Any idea guys? Thanks :
If you haven't done so already you probably need to set up a custom configuration section handler to parse the "InventoryFactory" section into your "ObjectFactoryConfiguration" object. The error message indicates that the runtime is trying to load the "WDG.ObjectFactory.ObjectFactoryConfiguration" class from the "System.Configuration" assembly which wouldn't contain any of your custom classes.
...Also, you want to specify the assembly in the section, if you look at the line right above yours:<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> you can see at the end there the "log4net" assembly has been specified. Try putting the name of your assembly which contains the "ObjectFactoryConfiguration" class in the type attribute as well.