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.
Related
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.
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();
}
}
I am trying to get ninject to work in a production environment.
My solution consists of the following projects
Data
Model
WebApi2
MVC5
Everything is getting deployed as webrole to azure.
My api is setup as a virtual application below the mvc site. My application is a multi tenant application so I want users to be able to access the api the same way as the application does e.g.
https://theirbusiness.mydomain.com/api/api-call
For my local development I am using 2 sites not a virtual application as I had to many issues trying to battle with azure to get it working locally. So my service definition has 2 sites created for local work. Locally I have no issues
My website and api both have reference to ninject, my data and model do not.
When I deploy and try to hit the api I get an error
The static container already has a kernel associated with it!
The website doesnt have any issues it just seems to be the api. I added ninject to both using nuget
The stack trace
[NotSupportedException: The static container already has a kernel associated with it!]
Ninject.Web.KernelContainer.set_Kernel(IKernel value) +193
Ninject.Web.NinjectWebHttpApplicationPlugin.Start() +82
Ninject.Web.Common.Bootstrapper.b__0(INinjectHttpApplicationPlugin c) +89
Ninject.Infrastructure.Language.ExtensionsForIEnumerableOfT.Map(IEnumerable1 series, Action1 action) +283
Ninject.Web.Common.Bootstrapper.Initialize(Func`1 createKernelCallback) +410
MyNameSpace.Application.Api.App_Start.NinjectWebCommon.Start() +362
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +417
System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +35
WebActivator.BaseActivationMethodAttribute.InvokeMethod() +761
WebActivator.ActivationManager.RunActivationMethods() +1177
WebActivator.ActivationManager.RunPreStartMethods() +75
WebActivator.ActivationManager.Run() +97
[InvalidOperationException: The pre-application start initialization method Run on type WebActivator.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures) +888
System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +137
System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +160
System.Web.Compilation.BuildManager.ExecutePreAppStart() +142
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +838
[HttpException (0x80004005): The pre-application start initialization method Run on type WebActivator.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +452
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +99
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +1017
My NinjectWebCommon.cs
using System;
using System.Web;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Common;
using MyNameSpace.Application.Api.App_Start;
using MyNameSpace.Application.Api.Interface;
using MyNameSpace.Application.Api.Repository;
[assembly: WebActivator.PreApplicationStartMethod(typeof(NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(NinjectWebCommon), "Stop")]
namespace MyNameSpace.Application.Api.App_Start
{
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
/// <summary>
/// Stops the application.
/// </summary>
public static void Stop()
{
bootstrapper.ShutDown();
}
/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(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<IBusinessRepository>().ToConstant(new BusinessRepository());
kernel.Bind<IEmployeeRepository>().ToConstant(new EmployeeRepository());
}
}
}
My Dependency scope
public class NinjectDependencyScope : IDependencyScope
{
private IResolutionRoot resolver;
internal NinjectDependencyScope(IResolutionRoot resolver)
{
Contract.Assert(resolver != null);
this.resolver = resolver;
}
public void Dispose()
{
IDisposable disposable = resolver as IDisposable;
if (disposable != null)
disposable.Dispose();
resolver = null;
}
public object GetService(Type serviceType)
{
if (resolver == null)
throw new ObjectDisposedException("this", "This scope has already been disposed");
return resolver.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
if (resolver == null)
throw new ObjectDisposedException("this", "This scope has already been disposed");
return resolver.GetAll(serviceType);
}
}
public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
{
private IKernel kernel;
public NinjectDependencyResolver(IKernel kernel)
: base(kernel)
{
this.kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(kernel.BeginBlock());
}
}
If I debug locally. Setting the api as my startup project I can run the application without any problems as soon as I deploy it, it fails. I remote logged into the azure webrole and deleted the mvc site keeping just the api site as the root site. This did not help the issue.
Does something look wrong in my above setup?
I believe your problem is the same as mine. The problem is that you have duplicate Ninject.dll or whatever dll from Ninject in your production environment. You have to clean all your existing files before you deploy again. See my solution here:
The static container already has a kernel associated with it
This happened to me, and I just commented on this line: bootstrapper.Initialize(CreateKernel) and the problem it's over.
I tried to inject dependencies into a controller's constructor, as i have previously. The problem is that i can't seem to get it to work. Is there any new requirement when doing DI with MVC 4 or am i missing some basic requirement ?
I'm using:
Ninject.MVC3 3.0.0.6
System.Web.MVC 4.0.0.0
Here are the important sections for that matter:
NinjectWebCommon.cs
public static class NinjectWebCommon{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
/// <summary>
/// Stops the application.
/// </summary>
public static void Stop()
{
bootstrapper.ShutDown();
}
/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
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<Handling.EventHandler>().To<EventDtoHandler>();
kernel.Bind<CommandHandler>().To<CommandDtoHandler>();
kernel.Bind<Mapper>().To<DtoMapper>().InSingletonScope();
kernel.Bind<Serializer>().To<DtoSerializer>();
kernel.Bind<Deserializer>().To<DtoDeserializer>();
kernel.Bind<CommandQueue>().To<DeviceCommandQueue>();
kernel.Bind<Dispatcher>().To<EventDispatcher>();
kernel.Bind<Instantiator>().To<DtoInstantiator>();
kernel.Bind<Template>().To<NmsTemplate>().InSingletonScope();
}
}
Global.asax:
public class Global : HttpApplication {
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?favicon.ico(/.*)?" });
routes.MapRoute(
"Event", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Event", action = "Event", id = UrlParameter.Optional } // Parameter defaults
);
}
}
The Controller:
public class EventController : Controller{
private readonly EventHandler eventDtoHandler;
public EventController(EventHandler eventDtoHandler){
this.eventDtoHandler = eventDtoHandler;
}
...
Some Actions
...
}
I get:
[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 'Web.Controllers.EventController'. 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
Seems to me that Ninject dont get the ControllerFactory responsibility..
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();