Unity MVC using SOA and gereric Repository and UnitOfWork - asp.net-mvc

I am trying to put together a project that is based on SOA and uses Gereric Repository and UnitOfWork along with Unity.
My problem is that when the controllers try to initialize I get the following error:
The type String cannot be constructed. You must configure the container to supply this value.
I have the following Unity Configuration:
public static class UnityConfig
{
#region Unity Container
private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});
/// <summary>
/// Gets the configured Unity container.
/// </summary>
public static IUnityContainer GetConfiguredContainer()
{
return container.Value;
}
#endregion
public static void RegisterTypes(IUnityContainer container)
{
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
container.RegisterType<IDataContextAsync, MyDbContext>(new PerRequestLifetimeManager())
.RegisterType<IRepositoryProvider, RepositoryProvider>(
new PerRequestLifetimeManager(),
new InjectionConstructor(new object[] { new RepositoryFactories() })
)
.RegisterType<IUnitOfWorkAsync, UnitOfWork>(new PerRequestLifetimeManager())
.RegisterType<IUnitOfWork, UnitOfWork>(new PerRequestLifetimeManager())
.RegisterType<IRepositoryAsync<ApplicationSetting>, Repository<ApplicationSetting>>()
.RegisterType<IApplicationSettingService, ApplicationSettingService>();
container.RegisterType<IRepositoryProvider, RepositoryProvider>(new InjectionConstructor(container));
}
}
The following Activator
using System.Linq;
using System.Web.Mvc;
using Microsoft.Practices.Unity.Mvc;
using XNETProductQuote.Web;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(UnityWebActivator), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(UnityWebActivator), "Shutdown")]
namespace XNETProductQuote.Web
{
/// <summary>Provides the bootstrapping for integrating Unity with ASP.NET MVC.</summary>
public static class UnityWebActivator
{
/// <summary>Integrates Unity when the application starts.</summary>
public static void Start()
{
var container = UnityConfig.GetConfiguredContainer();
FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
// TODO: Uncomment if you want to use PerRequestLifetimeManager
Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
}
/// <summary>Disposes the Unity container when the application is shut down.</summary>
public static void Shutdown()
{
var container = UnityConfig.GetConfiguredContainer();
container.Dispose();
}
}
}
My controller that I am trying to load is the following
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XNETProductQuote.Entities ;
using XNETProductQuote.Entities.Models;
using XNETProductQuote.Service;
namespace XNETProductQuote.Controllers
{
public class ApplicationSettingController : Controller
{
private IApplicationSettingService service;
public ApplicationSettingController(IApplicationSettingService svr)
{
service = svr;
}
//
// GET: /ApplicationSetting/
public ActionResult Index()
{
var applicationSettings = service.GetAll();
return View(applicationSettings);
}
}
As far as I can see the Unityconfig Registers the IApplicationSettingService type that should be used to initialise the controller.
am I missing something else?
UPDATE:
The error I get is
[InvalidOperationException: The type String cannot be constructed. You must configure the container to supply this value.]
Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.GuardTypeIsNonPrimitive(IBuilderContext context) +299
Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.PreBuildUp(IBuilderContext context) +131
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +274
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlanCreatorPolicy.CreatePlan(IBuilderContext context, NamedTypeBuildKey buildKey) +162
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +245
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +274
Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) +167
Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context) +101
lambda_method(Closure , IBuilderContext ) +222
Microsoft.Practices.ObjectBuilder2.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context) +71
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) +42
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +333
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +274
Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) +167
Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context) +101
lambda_method(Closure , IBuilderContext ) +232
Microsoft.Practices.ObjectBuilder2.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context) +71
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) +42
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +333
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +274
Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) +167
Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context) +101
lambda_method(Closure , IBuilderContext ) +222
Microsoft.Practices.ObjectBuilder2.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context) +71
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) +42
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +333
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +274
Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) +167
Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context) +101
lambda_method(Closure , IBuilderContext ) +224
Microsoft.Practices.ObjectBuilder2.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context) +71
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) +42
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +333
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +274
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides) +384
[ResolutionFailedException: Resolution of the dependency failed, type = "XNETProductQuote.Controllers.ApplicationSettingController", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type String cannot be constructed. You must configure the container to supply this value.
-----------------------------------------------
At the time of the exception, the container was:
Resolving XNETProductQuote.Controllers.ApplicationSettingController,(none)
Resolving parameter "svr" of constructor XNETProductQuote.Controllers.ApplicationSettingController(XNETProductQuote.Service.IApplicationSettingService svr)
Resolving XNETProductQuote.Service.ApplicationSettingService,(none) (mapped from XNETProductQuote.Service.IApplicationSettingService, (none))
Resolving parameter "repository" of constructor XNETProductQuote.Service.ApplicationSettingService(Repository.Pattern.Repositories.IRepositoryAsync`1[[XNETProductQuote.Entities.Models.ApplicationSetting, XNETProductQuote.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] repository)
Resolving Repository.Pattern.Ef6.Repository`1[XNETProductQuote.Entities.Models.ApplicationSetting],(none) (mapped from Repository.Pattern.Repositories.IRepositoryAsync`1[XNETProductQuote.Entities.Models.ApplicationSetting], (none))
Resolving parameter "context" of constructor Repository.Pattern.Ef6.Repository`1[[XNETProductQuote.Entities.Models.ApplicationSetting, XNETProductQuote.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]](Repository.Pattern.DataContext.IDataContextAsync context, Repository.Pattern.UnitOfWork.IUnitOfWorkAsync unitOfWork)
Resolving XNETProductQuote.Entities.MyDbContext,(none) (mapped from Repository.Pattern.DataContext.IDataContextAsync, (none))
Resolving parameter "connectionString" of constructor XNETProductQuote.Entities.MyDbContext(System.String connectionString)
Resolving System.String,(none)
]
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides) +447
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name, IEnumerable`1 resolverOverrides) +50
Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides) +48
Microsoft.Practices.Unity.UnityContainerExtensions.Resolve(IUnityContainer container, Type t, ResolverOverride[] overrides) +61
Microsoft.Practices.Unity.Mvc.UnityDependencyResolver.GetService(Type serviceType) +142
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +87
[InvalidOperationException: An error occurred when trying to create a controller of type 'XNETProductQuote.Controllers.ApplicationSettingController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +247
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +438
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +226
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +326
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +157
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +88
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +50
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
My Repository class is as follow
public static class ApplicationSettingRepository
{
public static ApplicationSetting GetByID(this IRepository<ApplicationSetting> repository, int applicationSettingId)
{
return repository.Find(applicationSettingId);
}
public static IEnumerable<ApplicationSetting> GetAll(this IRepository<ApplicationSetting> repository)
{
return repository.Queryable().AsEnumerable();
}
}

Related

When injecting service with IHttpFactory the constructor could not be located in Blazor server

I am trying to register a service which uses a IHttpClientFactory in the startup.cs. I get an exception when I access the page where I injected this service (it does start up). I tried using an HttpContext instead of a factory and then I do not get the following error.
Error:
InvalidOperationException: A suitable constructor for type
'dida.Data.Member.MemberService' could not be located.
Ensure the type is concrete and services are registered for all
parameters of a public constructor.
The service:
namespace dida.Data.Member
{
public class MemberService
{
private readonly IHttpClientFactory _clientFactory;
public MemberService(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
public async Task<IEnumerable<Member>> GetMembers()
{
var request = new HttpRequestMessage(HttpMethod.Get, "users?_token=*");
var client = _clientFactory.CreateClient("myapp");
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
using var responseStream = await response.Content.ReadAsStreamAsync();
return await JsonSerializer.DeserializeAsync<IEnumerable<Member>>(responseStream);
}
else
{
throw new HttpRequestException("No success status code, got the following: " + response.StatusCode);
}
}
}
}
Startup:
services.AddHttpClient<MemberService>("myapp", c =>
{
c.BaseAddress = new Uri("https://myapp.nl/api");
c.DefaultRequestHeaders.Add("User-Agent", "blazor-server");
});
Full log:
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.FindApplicableConstructor(Type instanceType, Type[] argumentTypes, out ConstructorInfo matchingConstructor, out Nullable<int>[] matchingParameterMap)
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateFactory(Type instanceType, Type[] argumentTypes)
Microsoft.Extensions.Http.DefaultTypedHttpClientFactory<TClient>+Cache+<>c.<.cctor>b__7_0()
System.Threading.LazyInitializer.EnsureInitializedCore<T>(ref T target, ref bool initialized, ref object syncLock, Func<T> valueFactory)
System.Threading.LazyInitializer.EnsureInitialized<T>(ref T target, ref bool initialized, ref object syncLock, Func<T> valueFactory)
Microsoft.Extensions.Http.DefaultTypedHttpClientFactory<TClient>+Cache.get_Activator()
Microsoft.Extensions.Http.DefaultTypedHttpClientFactory<TClient>.CreateClient(HttpClient httpClient)
Microsoft.Extensions.DependencyInjection.HttpClientBuilderExtensions+<>c__DisplayClass10_0<TClient>.<AddTypedClientCore>b__0(IServiceProvider s)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitDisposeCache(ServiceCallSite transientCallSite, RuntimeResolverContext context)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSite(ServiceCallSite callSite, TArgument argument)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine+<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
Microsoft.AspNetCore.Components.ComponentFactory+<>c__DisplayClass6_0.<CreateInitializer>g__Initialize|2(IServiceProvider serviceProvider, IComponent component)
Microsoft.AspNetCore.Components.ComponentFactory.PerformPropertyInjection(IServiceProvider serviceProvider, IComponent instance)
Microsoft.AspNetCore.Components.ComponentFactory.InstantiateComponent(IServiceProvider serviceProvider, Type componentType)
Microsoft.AspNetCore.Components.RenderTree.Renderer.InstantiateChildComponentOnFrame(ref RenderTreeFrame frame, int parentComponentId)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewComponentFrame(ref DiffContext diffContext, int frameIndex)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewSubtree(ref DiffContext diffContext, int frameIndex)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InsertNewFrame(ref DiffContext diffContext, int newFrameIndex)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForRange(ref DiffContext diffContext, int oldStartIndex, int oldEndIndexExcl, int newStartIndex, int newEndIndexExcl)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.ComputeDiff(Renderer renderer, RenderBatchBuilder batchBuilder, int componentId, ArrayRange<RenderTreeFrame> oldTree, ArrayRange<RenderTreeFrame> newTree)
Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder batchBuilder, RenderFragment renderFragment)
Microsoft.AspNetCore.Components.RenderTree.Renderer.RenderInExistingBatch(RenderQueueEntry renderQueueEntry)
Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue()
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.HandleException(Exception exception)
Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue()
Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessPendingRender()
Microsoft.AspNetCore.Components.RenderTree.Renderer.AddToRenderQueue(int componentId, RenderFragment renderFragment)
Microsoft.AspNetCore.Components.ComponentBase.StateHasChanged()
Microsoft.AspNetCore.Components.ComponentBase.CallOnParametersSetAsync()
Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.HandleException(Exception exception)
Microsoft.AspNetCore.Components.RenderTree.Renderer.AddToPendingTasks(Task task)
Microsoft.AspNetCore.Components.Rendering.ComponentState.SetDirectParameters(ParameterView parameters)
Microsoft.AspNetCore.Components.RenderTree.Renderer.RenderRootComponentAsync(int componentId, ParameterView initialParameters)
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.CreateInitialRenderAsync(Type componentType, ParameterView initialParameters)
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.RenderComponentAsync(Type componentType, ParameterView initialParameters)
Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContext+<>c__11<TResult>+<<InvokeAsync>b__11_0>d.MoveNext()
Microsoft.AspNetCore.Mvc.ViewFeatures.StaticComponentRenderer.PrerenderComponentAsync(ParameterView parameters, HttpContext httpContext, Type componentType)
Microsoft.AspNetCore.Mvc.ViewFeatures.ComponentRenderer.PrerenderedServerComponentAsync(HttpContext context, ServerComponentInvocationSequence invocationId, Type type, ParameterView parametersCollection)
Microsoft.AspNetCore.Mvc.ViewFeatures.ComponentRenderer.RenderComponentAsync(ViewContext viewContext, Type componentType, RenderMode renderMode, object parameters)
Microsoft.AspNetCore.Mvc.TagHelpers.ComponentTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.<RunAsync>g__Awaited|0_0(Task task, TagHelperExecutionContext executionContext, int i, int count)
dida.Pages.Pages__Host.<ExecuteAsync>b__14_1() in _Host.cshtml
+
<component type="typeof(App)" render-mode="ServerPrerendered" />
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.SetOutputContentAsync()
dida.Pages.Pages__Host.ExecuteAsync() in _Host.cshtml
+
Layout = null;
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0<TFilter, TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
To use your class the way you originally have it defined with the IHttpClientFactory, you would need to register/configure it differently.
Like this
//adding named client
services.AddHttpClient("myapp", c => {
c.BaseAddress = new Uri("https://myapp.nl/api");
c.DefaultRequestHeaders.Add("User-Agent", "blazor-server");
});
//adding regular service
services.AddScoped<MemberService>();
Reference Make HTTP requests using IHttpClientFactory in ASP.NET Core
However, you are mixing up how to use typed clients since you register you class like this
services.AddHttpClient<MemberService>("myapp", c => ....
Note
A Typed Client is a class that accepts an HttpClient object (injected through its constructor) and uses it to call some remote HTTP service.
Reference Use IHttpClientFactory to implement resilient HTTP requests
For example
public class MemberService
{
private readonly HttpClient client;
public MemberService(HttpClient client) {
this.client = client;
}
public async Task<IEnumerable<Member>> GetMembers() {
var request = new HttpRequestMessage(HttpMethod.Get, "users?_token=*");
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode) {
using var responseStream = await response.Content.ReadAsStreamAsync();
return await JsonSerializer.DeserializeAsync<IEnumerable<Member>>(responseStream);
} else {
throw new HttpRequestException("No success status code, got the following: " + response.StatusCode);
}
}
}
So because you registered your class as a typed client but did not have the corresponding constructor, you got the stated error.

Can't insert data into my database

I'm taking a tutorial in ASP.NET Core and Entity framework and I can't insert data into my database. I've found that whenever I comment the line:
DbInitializer.Initialize(context);
The Aplication works.
This line is in the Startup.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ContosoUniversity.Data;
using Microsoft.EntityFrameworkCore;
namespace ContosoUniversity
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<SchoolContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SchoolContext context)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
DbInitializer.Initialize(context);
}
}
}
This is the error message I get when I launch the web app
An error occurred while starting the application.
ArgumentException: Keyword not supported: '"server'.
System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary<string, string> parsetable, string connectionString, bool buildChain, Dictionary<string, string> synonyms)
ArgumentException: Keyword not supported: '"server'.
System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary<string, string> parsetable, string connectionString, bool buildChain, Dictionary<string, string> synonyms)
System.Data.Common.DbConnectionOptions..ctor(string connectionString, Dictionary<string, string> synonyms)
System.Data.SqlClient.SqlConnectionString..ctor(string connectionString)
System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(string connectionString, DbConnectionOptions previous)
System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, ref DbConnectionOptions userConnectionOptions)
System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key)
System.Data.SqlClient.SqlConnection.set_ConnectionString(string value)
Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerConnection.CreateDbConnection()
Microsoft.EntityFrameworkCore.Internal.LazyRef.get_Value()
Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open()
Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerDatabaseCreator+<>c__DisplayClass11_0.<Exists>b__0(DateTime giveUp)
Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute<TState, TResult>(Func<TState, TResult> operation, Func<TState, ExecutionResult<TResult>> verifySucceeded, TState state)
Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute<TState, TResult>(IExecutionStrategy strategy, Func<TState, TResult> operation, TState state)
Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.EnsureCreated()
ContosoUniversity.Data.DbInitializer.Initialize(SchoolContext context) in DbInitializer.cs
-
namespace ContosoUniversity.Data
{
public static class DbInitializer
{
public static void Initialize(SchoolContext context)
{
context.Database.EnsureCreated();
// Look for any students.
if (context.Students.Any())
{
return; // DB has been seeded
}
var students = new Student[]
ContosoUniversity.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SchoolContext context) in Startup.cs
-
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
DbInitializer.Initialize(context);
}
}
}
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
Show raw exception details
System.ArgumentException: Keyword not supported: '"server'.
at System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary`2 parsetable, String connectionString, Boolean buildChain, Dictionary`2 synonyms)
at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary`2 synonyms)
at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous)
at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions)
at System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key)
at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerConnection.CreateDbConnection()
at Microsoft.EntityFrameworkCore.Internal.LazyRef`1.get_Value()
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open()
at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerDatabaseCreator.<>c__DisplayClass11_0.<Exists>b__0(DateTime giveUp)
at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](Func`2 operation, Func`2 verifySucceeded, TState state)
at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, Func`2 operation, TState state)
at Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.EnsureCreated()
at ContosoUniversity.Data.DbInitializer.Initialize(SchoolContext context) in C:\Users\iderlich\OneDrive\Documentos.Kerberos\Practica MVC\VS2017 PC Talca\ContosoUniversity\ContosoUniversity\Data\DbInitializer.cs:line 10
at ContosoUniversity.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SchoolContext context) in C:\Users\iderlich\OneDrive\Documentos.Kerberos\Practica MVC\VS2017 PC Talca\ContosoUniversity\ContosoUniversity\Startup.cs:line 62
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
.NET Core X64 v4.1.1.0 | Microsoft.AspNetCore.Hosting version 1.1.2 | Microsoft Windows 6.1.7601 S | Need help?
Your connection string is bad. Server should be Data Source.
Also remove the quotes from the connection string.

Hangfire: The invoked member is not supported in a dynamic assembly

I'm trying to use Hangfire in my ASP MVC application, I have configured my application as follows:
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseHangfire(config =>
{
config.UseSqlServerStorage("myconnstring");
config.UseServer();
});
}
}
But I'm getting the following error every time I run my app:
[NotSupportedException: The invoked member is not supported in a dynamic assembly.]
System.Reflection.Emit.InternalAssemblyBuilder.get_Location() +56
log4net.Util.SystemInfo.AssemblyLocationInfo(Assembly myAssembly) +88
log4net.Core.DefaultRepositorySelector.GetInfoForAssembly(Assembly assembly, String& repositoryName, Type& repositoryType) +256
log4net.Core.DefaultRepositorySelector.CreateRepository(Assembly repositoryAssembly, Type repositoryType, String repositoryName, Boolean readAssemblyAttributes) +270
log4net.Core.DefaultRepositorySelector.CreateRepository(Assembly repositoryAssembly, Type repositoryType) +58
log4net.Core.DefaultRepositorySelector.GetRepository(Assembly repositoryAssembly) +115
log4net.Core.LoggerManager.GetLogger(Assembly repositoryAssembly, String name) +180
log4net.LogManager.GetLogger(Assembly repositoryAssembly, String name) +50
log4net.LogManager.GetLogger(String name) +55
lambda_method(Closure , String ) +39
Hangfire.Logging.LogProviders.Log4NetLogProvider.GetLogger(String name) +50
Hangfire.Logging.LogProvider.GetLogger(String name) +103
Hangfire.Logging.LogProvider.GetLogger(Type type) +53
Hangfire.SqlServer.SqlServerObjectsInstaller..cctor() +65

Structuremap does not work on MVC4

I've used StructureMap in MVC2/3 many times without any concern, but I guess handling IoC is different in MVC4.
When i used StructureMap for handling IoC in MVC4 I get the following exception.:
No parameterless constructor defined for this object
Why?
I have not found any correct result in google except this: IoC Not Working In MVC4
These is my IoC classes:
public static class IoC {
public static IContainer Initialize() {
ObjectFactory.Initialize(x =>
{
x.Scan(scan =>
{
//scan.Assembly("DLL.Core");
scan.Assembly("DLL.CMS");
scan.TheCallingAssembly();
scan.WithDefaultConventions();
});
x.For<IDbContext>().Use<ModelEntities>();
x.For(typeof(IRepository<>)).Use(typeof(Repository<>));
x.For<IHttpControllerActivator>();
x.For<IController>();
});
return ObjectFactory.Container;
}
And SmDependencyResolver is:
public class SmDependencyResolver : IDependencyResolver
{
private readonly IContainer _container;
public SmDependencyResolver(IContainer container)
{
_container = container;
}
public object GetService(Type serviceType)
{
if (serviceType == null) return null;
try
{
return serviceType.IsAbstract || serviceType.IsInterface
? _container.TryGetInstance(serviceType)
: _container.GetInstance(serviceType);
}
catch
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.GetAllInstances(serviceType).Cast<object>();
}
}
And my error is:
No parameterless constructor defined for this object.
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.MissingMethodException: No parameterless constructor defined for this object.
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.
Stack Trace:
[MissingMethodException: No parameterless constructor defined for this
object.] System.RuntimeTypeHandle.CreateInstance(RuntimeType type,
Boolean publicOnly, Boolean noCheck, Boolean& canBeCached,
RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean
skipCheckThis, Boolean fillCache) +98
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly,
Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean
fillCache) +241 System.Activator.CreateInstance(Type type, Boolean
nonPublic) +69
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext
requestContext, Type controllerType) +67
[InvalidOperationException: An error occurred when trying to create a
controller of type
'Parsian.Web.Areas.Dashboard.Controllers.MemberController'. Make sure
that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext
requestContext, Type controllerType) +182
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext
requestContext, Type controllerType) +80
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext
requestContext, String controllerName) +74
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase
httpContext, IController& controller, IControllerFactory& factory)
+196 System.Web.Mvc.<>c__DisplayClass6.b__2() +49 System.Web.Mvc.<>c__DisplayClassb1.<ProcessInApplicationTrust>b__a()
+13 System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action
action) +22
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func1 func)
+124 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +98
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext,
AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext
context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+8862676 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Thanks for correct answers.
oops.I found an emergency solution :) Try to implement a class from IControllerActivator
public class StructureMapControllerActivator : IControllerActivator
{
private IContainer _container;
public StructureMapControllerActivator(IContainer container)
{
_container = container;
}
public IController Create(RequestContext requestContext, Type controllerType)
{
return _container.GetInstance(controllerType) as IController;
}
}
and then register it to the IoC class:
x.For<IControllerActivator>().Use<StructureMapControllerActivator>();
and then enjoy it.
Good luck
If you remove any old configuration for structuremap and install structurmap.mvc4 from nuget then configure your IoC container, you don't have any problems.
try adding this class as your ControllerFactory, I've actually seen the error above in MVC3 and this usually fixed it for me
public class StructureMapControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
try
{
return (controllerType == null)
? base.GetControllerInstance(requestContext, controllerType)
: ObjectFactory.GetInstance(controllerType) as IController;
}
catch (Exception ex)
{
return null;
}
}
}
Using StructureMap.MVC5.Update I had to do this or else the nested IContainer was already disposed (weird) :
public class StructureMapControllerActivator : IControllerActivator
{
public IController Create(RequestContext requestContext, Type controllerType)
{
return StructuremapMvc.StructureMapDependencyScope.GetInstance(controllerType) as IController;
}
}

Ninject + "Error loading Ninject component ICache"

I've just installed the new Ninject.MVC3 from NuGet and trying to make it work in my asp.net mvc 3 app, however I get this weird error now and then when surfing my site:
[InvalidOperationException: Error loading Ninject component ICache
No such component has been registered in the kernel's component container.
Suggestions:
1) If you have created a custom subclass for KernelBase, ensure that you have properly
implemented the AddComponents() method.
2) Ensure that you have not removed the component from the container via a call to RemoveAll().
3) Ensure you have not accidentally created more than one kernel.
]
Ninject.Components.ComponentContainer.Get(Type component) in d:\BuildAgent-01\work\b68efe9aafe8875e\src\Ninject\Components\ComponentContainer.cs:146
Ninject.Components.ComponentContainer.Get() in d:\BuildAgent-01\work\b68efe9aafe8875e\src\Ninject\Components\ComponentContainer.cs:102
Ninject.KernelBase.CreateContext(IRequest request, IBinding binding) in d:\BuildAgent-01\work\b68efe9aafe8875e\src\Ninject\KernelBase.cs:540
Ninject.<>c__DisplayClassa.<Resolve>b__6(IBinding binding) in d:\BuildAgent-01\work\b68efe9aafe8875e\src\Ninject\KernelBase.cs:375
System.Linq.<>c__DisplayClass12`3.<CombineSelectors>b__11(TSource x) +20
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +151
System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source) +4178557
Ninject.Web.Mvc.NinjectDependencyResolver.GetService(Type serviceType) in c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectDependencyResolver.cs:56
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +51
[InvalidOperationException: An error occurred when trying to create a controller of type 'MyApp.Controllers.NewsController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +182
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +74
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +196
System.Web.Mvc.<>c__DisplayClass6.<BeginProcessRequest>b__2() +49
System.Web.Mvc.<>c__DisplayClassb`1.<ProcessInApplicationTrust>b__a() +13
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func`1 func) +124
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +98
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8862580
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
And my code is:
// AppStart_NinjectMVC3.cs
using System.Web.Mvc;
using Ninject.Modules;
[assembly: WebActivator.PreApplicationStartMethod(typeof(MyApp.AppStart_NinjectMVC3), "Start")]
namespace MyApp
{
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
public static class AppStart_NinjectMVC3
{
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpApplicationModule));
}
}
}
// NinjectHttpApplicationModule.cs
using MyApp.Data;
using NHibernate;
namespace MyApp
{
using System;
using System.Web;
using Ninject;
using Ninject.Web.Mvc;
public sealed class NinjectHttpApplicationModule : IHttpModule, IDisposable
{
#region Ninject Mvc3 extension bootstrapper (Do not touch this code)
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
private static bool initialized;
private static bool kernelDisposed;
/// <summary>
/// Initializes a module and prepares it to handle requests.
/// Do not change this method!
/// </summary>
/// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application</param>
public void Init(HttpApplication context)
{
lock (bootstrapper)
{
if (initialized)
{
return;
}
initialized = true;
bootstrapper.Initialize(CreateKernel);
}
}
/// <summary>
/// Disposes the <see cref="T:System.Web.HttpApplication"/> instance.
/// Do not change this method!
/// </summary>
public void Dispose()
{
lock (bootstrapper)
{
if (kernelDisposed)
{
return;
}
kernelDisposed = true;
bootstrapper.ShutDown();
}
}
#endregion
/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
RegisterServices(kernel);
return kernel;
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<ISession>().ToMethod(x => kernel.Get<SessionFactoryBuilder>().CreateFactory().OpenSession()).InRequestScope();
kernel.Bind<ITransaction>().ToMethod(x => kernel.Get<ISession>().BeginTransaction()).InRequestScope();
kernel.Bind(typeof(IRepositoryBase<>)).To(typeof(RepositoryBase<>));
kernel.Bind<IUnitOfWork>().To<UnitOfWork>();
}
}
}
Most of the code is the default one you get when installing by NuGet.. the only thing I've done is to add some bindings to the RegisterServices()
Any suggestions?
Fixed in 2.2.1.0
See http://www.planetgeek.ch/2011/03/01/ninject-2-2-1-0-and-ninject-mvc3-2-2-1-0-released/ for more information.
Looks like its a bug according to this thread, and that they are working on a fix...
Like previously mentioned it does look like a bug.
One option is to simply implement a singleton extension method yourself:
public static class NinjectSingletonExtension
{
public static CustomSingletonKernelModel<T> SingletonBind<T>(this IKernel i_KernelInstance)
{
return new CustomSingletonKernelModel<T>(i_KernelInstance);
}
}
public class CustomSingletonKernelModel<T>
{
private const string k_ConstantInjectionName = "Implementation";
private readonly IKernel _kernel;
private static object padlock = new Object();
private T _concreteInstance;
public CustomSingletonKernelModel(IKernel i_KernelInstance)
{
this._kernel = i_KernelInstance;
}
public IBindingInNamedWithOrOnSyntax<T> To<TImplement>(TImplement i_Constant = null) where TImplement : class, T
{
_kernel.Bind<T>().To<TImplement>().Named(k_ConstantInjectionName);
var toReturn =
_kernel.Bind<T>().ToMethod(x =>
{
if (i_Constant != null)
{
return i_Constant;
}
if (_concreteInstance == null)
{
lock (padlock)
{
if (_concreteInstance == null)
{
_concreteInstance = _kernel.Get<T>(k_ConstantInjectionName);
}
}
}
return _concreteInstance;
}).When(x => true);
return toReturn;
}
}
And then simply use:
i_Kernel.SingletonBind<T>().To<TImplement>();
Rather then
i_Kernel.Bind<T>().To<TImplement>().InSingletonScope();

Resources