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])'.
Related
I'm working on adding propagation to HotChocolate GraphQL server but simply can't get it working.
I've configured my propagation in my ConfigureServices services.AddHeaderPropagation(o => o.Headers.Add("Authorization"));
I've added it to my httpClient: services.AddHttpClient(AssumptionManagement, c => c.BaseAddress = new Uri("http://localhost:19801")).AddHeaderPropagation();
I've added it in my Configure method:
app.UseHeaderPropagation();
Despite all this it still gives me the following error when I run the app in debug:
An unhandled exception of type System.InvalidOperationException occurred in System.Private.CoreLib.dll: The HeaderPropagationValues.Headers property has not been initialized.
Register the header propagation middleware by adding app.UseHeaderPropagation() in the Configure(...) method. Header propagation can only be used within the context of an HTTP request.'
Am I just not seeing something here or what am I doing wrong?
Problem I'm dealing with, is weird error :
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: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.)
it happens whenever any method with db is called, like:
foo()
{
return _dbContext.data.ToList();
}
File db was created automatically based on code first approach and connection string:
<add name="Context"
connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\RestApi.Services.Context.mdf;Initial Catalog=RestApi.Services.Context;Integrated Security=True"
providerName="System.Data.SqlClient" />
I can connect with no errors to that file by VS server explorer.
On same PC I've runned several others apps with file db without any errors.
When I watch "Context" var in debbuger it seems connected to proper DB, but have error on workspaceID.
Now I'm stuck and don't have any idea how to fix it. :(
UnityConfig:
public static void RegisterComponents()
{
var container = new UnityContainer();
container.RegisterType<Context, Context>(new PerThreadLifetimeManager());
container.RegisterType<IXService, XService>();
DependencyResolver.SetResolver(new Unity.Mvc5.UnityDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
}
Context class:
public class Context : DbContext
{
public Context() : base("name=Context")
{
}
public DbSet<X> Xs{ get; set; }
public DbSet<Z> Zs{ get; set; }
public DbSet<Y> Ys{ get; set; }
}
EDIT
File Db was not the problem, I've tried with normal db connection string, and errors still occur.
I've tried many different solutions and no one works :(
now after change in UnityConfig:
public static void RegisterComponents()
{
var container = new UnityContainer();
container.RegisterType<DbContext, Context>();
container.RegisterType<IXService, XService>();
DependencyResolver.SetResolver(new Unity.Mvc5.UnityDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
}
first db read:
InvalidOperationException: The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.
next ones:
NullReferenceException: Object reference not set to an instance of an object.
EDIT2
Docker support was causing problems ;/ I'll upload solution when I find one
make sure that connectionstring data source is valid server name. if server name is valid then follow this instruction, this may help you.
Open "SQL Server Configuration Manager"
Now Click on "SQL Server Network Configuration" and Click on "Protocols for Name"
Right Click on "TCP/IP" (make sure it is Enabled) Click on Properties
Now Select "IP Addresses" Tab -and- Go to the last entry "IP All"
Enter "TCP Port" 1433.
Now Restart "SQL Server .Name." using "services.msc" (winKey + r)
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);
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>();
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");