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>();
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])'.
We use swagger for explore api and one time we turned off razor.
And this led to problem with swagger
Original error:
An unhandled exception occurred while processing the request.
DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'
on type 'Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator' can be invoked with the available services and parameters:
Cannot resolve parameter 'Microsoft.AspNetCore.Mvc.ApiExplorer.IApiDescriptionGroupCollectionProvider apiDescriptionsProvider'
of constructor 'Void .ctor(Microsoft.AspNetCore.Mvc.ApiExplorer.IApiDescriptionGroupCollectionProvider, Swashbuckle.AspNetCore.SwaggerGen.ISchemaRegistryFactory, Microsoft.Extensions.Options.IOptions`1[Swashbuckle.AspNetCore.SwaggerGen.SwaggerGeneratorOptions])'.
Cannot resolve parameter 'Microsoft.AspNetCore.Mvc.ApiExplorer.IApiDescriptionGroupCollectionProvider apiDescriptionsProvider'
of constructor 'Void .ctor(Microsoft.AspNetCore.Mvc.ApiExplorer.IApiDescriptionGroupCollectionProvider, Swashbuckle.AspNetCore.SwaggerGen.ISchemaRegistryFactory, Swashbuckle.AspNetCore.SwaggerGen.SwaggerGeneratorOptions)'.
Autofac.Core.Activators.Reflection.ReflectionActivator.GetValidConstructorBindings(IComponentContext context, IEnumerable<Parameter> parameters)
How the problem appeared: we used services.AddMvcCore instead services.AddMvc
How resolve: add registration of ApiExplorer
For example:
services.AddMvcCore()
.AddJsonFormatters()
.AddApiExplorer(); // this line is solution of problem
I used AddMvc() and it got resolved
For example:
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
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");
I'm building an asp.Net MVC application with Code First EntityFramework. I'm using Dependency Injection with Unity Container.
I have a context class like this
public partial class MyContext : DbContext
{
public MyContext()
: base("name=MyConnString")
{
Database.SetInitializer<MyContext>(null);
}
}
A Repository class like this:
public class Repository
{
public Repository(DbContext dataContext)
{
}
}
In Bootstrapper class I have this:
container.RegisterType<DbContext, MyContext>("DbContext",new HierarchicalLifetimeManager());
When I run the application, it throw this Exception:
The current type, System.Data.Common.DbConnection, is an abstract class > and cannot be constructed. Are you missing a type mapping?
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The current type, System.Data.Common.DbConnection, is an abstract class and cannot be constructed. Are you missing a type mapping?
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
The current type, System.Data.Common.DbConnection, is an abstract class and cannot be constructed. Are you missing a type mapping?
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The current type, System.Data.Common.DbConnection, is an abstract class and cannot be constructed. Are you missing a type mapping?
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
After research I found that this error is because Unity uses the most verbose constructor by default.
I need use the second constructor, but I don't know how configure Unity
Have you any idea?
You're looking for InjectionConstructor:
public partial class MyContext : DbContext
{
[InjectionConstructor]
public MyContext()
: base("name=MyConnString")
{
Database.SetInitializer<MyContext>(null);
}
}
You may also find this useful reading: https://msdn.microsoft.com/en-us/library/ff650802.aspx
Using Unity / Bootstrapper, I'm registering my base class - ServiceBase to multiple concrete services.
container.RegisterType<ServiceBase, ClearedPaymentService>("ClearedPaymentService");
container.RegisterType<ServiceBase, MissedPaymentService>("MissedPaymentService");
I'm also registering an external service below this:
container.RegisterType<IPaymentService, PaymentServiceClient>("PaymentService");
The external service is used in both the ClearedPaymentService and MissedPaymentService as shown below:
public partial class ClearedPaymentService : ServiceBase
{
private readonly IPaymentService _paymentService;
private readonly IScheduler _scheduler;
private Timer _timer;
public ClearedPaymentService(IPaymentService paymentService, IScheduler scheduler)
{
_paymentService = paymentService;
_scheduler = scheduler;
}
...etc
}
When I come to use my 2 services, I run into trouble:
var container = (IUnityContainer)Bootstrapper.Container;
var services = container.ResolveAll<ServiceBase>();
if (Environment.UserInteractive)
{
RunInteractive(services.ToArray());
}
The code throws an exception on "services.ToArray()":
Resolution of the dependency failed, type = "System.ServiceProcess.ServiceBase", name = "ClearedPaymentService".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, Think.IncomeProtection.ThirdParty.Service.Contract.Outbound.IPaymentService, is an interface and cannot be constructed. Are you missing a type mapping?
At the time of the exception, the container was:
Resolving ThirdPartyPaymentInvoker.ClearedPaymentService,ClearedPaymentService (mapped from System.ServiceProcess.ServiceBase, ClearedPaymentService)
Resolving parameter "paymentService" of constructor ThirdPartyPaymentInvoker.ClearedPaymentService(Think.IncomeProtection.ThirdParty.Service.Contract.Outbound.IPaymentService paymentService, ThirdPartyPaymentInvoker.IScheduler scheduler)
Resolving Think.IncomeProtection.ThirdParty.Service.Contract.Outbound.IPaymentService,(none)
I understand what the error is saying - the constructor of ClearedPaymentService is expecting a concrete instance of IPaymentService, but it hasn't been resolved for some reason...
I'm fairly new to Unity, so presume it's something basic that I haven't understood yet!
Any help appreciated.
Thanks,
Alex
Your registrations to container provide a name for each service that is registered. So basically there is no default (not named) service that Unity can use in your scenario.
To fix this just remove the names while registering thins. If on other hand you wish to use specific named service then there is an attribute that you can add on parameter of your constructor [NamedDependancy("Your name")]. But by default you should not use this feature the code is simpler without it.