Search Results

Search found 179 results on 8 pages for 'ninject'.

Page 2/8 | < Previous Page | 1 2 3 4 5 6 7 8  | Next Page >

  • Ninject 3.0 MVC kernel.bind error Auto Registration

    - by user295734
    Getting and error on kernel.Bind(scanner = ... "scanner" has the little error line under it in VS 2010. Cannot convert lambda expression to type 'System.Type[]' because it is not a delegate type Tyring to Auto Register like the old kernel.scan in 2.0. I can not figure out what i am doing wrong. Added and removed so many Ninject packages. completely lost, getting to be a big waste of time. using System; using System.Web; using Microsoft.Web.Infrastructure.DynamicModuleHelper; using Ninject; using Ninject.Web.Common; //using Ninject.Extensions.Conventions; using Ninject.Web.WebApi; using Ninject.Web.Mvc; using CommonServiceLocator.NinjectAdapter; using System.Reflection; using System.IO; using LR.Repository; using LR.Repository.Interfaces; using LR.Service.Interfaces; using System.Web.Http; 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(scanner => scanner.FromAssembliesInPath(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)) .Select(IsServiceType) .BindToDefaultInterface() .Configure(binding => binding.InSingletonScope()) ); } private static bool IsServiceType(Type type) { // temp return true; // .Any() is not recognized either. return true; // type.IsClass && type.GetInterfaces().Any(intface => intface.Name == "I" + type.Name); }

    Read the article

  • One Controller is Sometimes Bound Twice with Ninject

    - by Dusda
    I have the following NinjectModule, where we bind our repositories and business objects: /// <summary> /// Used by Ninject to bind interface contracts to concrete types. /// </summary> public class ServiceModule : NinjectModule { /// <summary> /// Loads this instance. /// </summary> public override void Load() { //bindings here. //Bind<IMyInterface>().To<MyImplementation>(); Bind<IUserRepository>().To<SqlUserRepository>(); Bind<IHomeRepository>().To<SqlHomeRepository>(); Bind<IPhotoRepository>().To<SqlPhotoRepository>(); //and so on //business objects Bind<IUser>().To<Data.User>(); Bind<IHome>().To<Data.Home>(); Bind<IPhoto>().To<Data.Photo>(); //and so on } } And here are the relevant overrides from our Global.asax, where we inherit from NinjectHttpApplication in order to integrate it with Asp.Net Mvc (The module lies in a separate dll called Thing.Web.Configuration): protected override void OnApplicationStarted() { base.OnApplicationStarted(); //routes and areas AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); //Initializes a singleton that must reference this HttpApplication class, //in order to provide the Ninject Kernel to the rest of Thing.Web. This //is necessary because there are a few instances (currently Membership) //that require manual dependency injection. NinjectKernel.Instance = new NinjectKernel(this); //view model factory. NinjectKernel.Instance.Kernel.Bind<IModelFactory>().To<MasterModelFactory>(); } protected override NinjectControllerFactory CreateControllerFactory() { return base.CreateControllerFactory(); } protected override Ninject.IKernel CreateKernel() { var kernel = new StandardKernel(); kernel.Load("Thing.Web.Configuration.dll"); return kernel; } Now, everything works great, with one exception: For some reason, sometimes Ninject will bind the PhotoController twice. This leads to an ActivationException, because Ninject can't discern which PhotoController I want. This causes all requests for thumbnails and other user images on the site to fail. Here is the PhotoController in it's entirety: public class PhotoController : Controller { public PhotoController() { } public ActionResult Index(string id) { var dir = Server.MapPath("~/" + ConfigurationManager.AppSettings["UserPhotos"]); var path = Path.Combine(dir, id); return base.File(path, "image/jpeg"); } } Every controller works in exactly the same way, but for some reason the PhotoController gets double-bound. Even then, it only happens occasionally (either when re-building the solution, or on staging/production when the app pool kicks in). Once this happens, it continues to happen until I redeploy without changing anything. So...what's up with that?

    Read the article

  • Using Prism with Ninject

    - by stiank81
    Is anyone out there using the Prism framework with Ninject instead of Unity? I need some functionality Unity isn't supporting yet, and I've decided to switch the IoC container to Ninject. I'm struggling a bit with the replace though.. What I need to use from Prism is the EventAggregator and the RegionManager. I have seen this sample that actually does the replace, but this is written for an older version of Prism, and several of the classes seems to have changed etc. So I ended up all confused after looking doing some effort in trying to rewrite it. So - my question is basically: How can I replace Unity with Ninject? What are the necessary steps? Initially I assumed I could write a simple bootstrapper that creates and configures a Ninject container and uses this to resolve all other objects. I bind IEventAggregator to EventAggregator and IRegionManager to RegionManager, but it fails when creating the Shell and the RegionManager.CreateRegion is called. Problem is that it seems like I need to set a ServiceLocator somewhere as it fails on this line: IServiceLocator locator = ServiceLocator.Current; Any ideas and tips along the way?

    Read the article

  • Using the Ninject NLogModule Logger in global.asax

    - by Ciaran
    I'm using Ninject for DI in my asp.net application, so my Global class inherits from NinjectHttpApplication. In my CreateKernel(), I'm creating my custom modules and DI is working fine for me. However, I notice that there is a Logger property in the NinjectHttpApplication class, so I'm trying to use this in Application_Error whenever an exception is not caught. I think I'm creating the nlog module correctly for Ninject, but my logger is always null. Here's my CreateKernel: protected override Ninject.Core.IKernel CreateKernel() { IKernel kernel = new StandardKernel(new NLogModule(), new NinjectRepositoryModule()); return kernel; } But in the following method, Logger is always null. protected void Application_Error(object sender, EventArgs e) { Exception lastException = Server.GetLastError().GetBaseException(); Logger.Error(lastException, "An exception was caught in Global.asax"); } To clarify, Logger is a property on NinjectHttpApplication of type ILogger and has the [Inject] attribute Any idea how to inject correctly into Logger?

    Read the article

  • Ninject with MembershipProvider | RoleProvider

    - by DVark
    I'm using ninject as my IoC and I wrote a role provider as follows: public class BasicRoleProvider : RoleProvider { private IAuthenticationService authenticationService; public BasicRoleProvider(IAuthenticationService authenticationService) { if (authenticationService == null) throw new ArgumentNullException("authenticationService"); this.authenticationService = authenticationService; } /* Other methods here */ } I read that Provider classes get instantiated before ninject gets to inject the instance. How do I go around this? I currently have this ninject code: Bind<RoleProvider>().To<BasicRoleProvider>().InRequestScope(); From this answer here. If you mark your dependencies with [Inject] for your properties in your provider class, you can call kernel.Inject(MemberShip.Provider) - this will assign all dependencies to your properties. I do not understand this.

    Read the article

  • Ninject and Custom Controller Factory

    - by Baddie
    I'm using MEF with ASP.NET MVC as demonstrated at http://blog.maartenballiauw.be/post/2009/06/17/Revised-ASPNET-MVC-and-the-Managed-Extensibility-Framework-(MEF).aspx. When I try to use Ninject, it seems that nothing gets injected. I did some debugging, and when I reverted to the original controller factory the injection worked. What needs to be changed, or what does Ninject need in terms of controller factories for it to work?

    Read the article

  • How to approach ninject container/kernel in inheritance situation

    - by Bas
    I have the following situation: class RuleEngine {} abstract class RuleImplementation {} class RootRule : RuleImplementation {} class Rule1 : RuleImplementation {} class Rule2 : RuleImplementation {} The RuleEngine is injected by Ninject and has a kernel at it's disposal, the role of the RuleEngine is to fire off the root rule, which on it's turn will load all the other rules also using Ninject, but using a different Module and creating a new Kernel. Now my question is, some of the rules require some dependencies which I want to inject using Ninject. What would be the best way to create the kernel for these rules and also still do proper unit testing with it? (the kernel shouldn't become a real pain in my tests) I've been thinking of the following possibilitys: The kernel that I use in the RuleEngine class could be tossed around to RuleImplementation and thus be available for every rule. But tossing around Kernels isn't really something I wish to do. When creating the rules, I could give the kernel (which creates the rules) as a constructor argument for each rule. I could create a method inside the RuleImplementation which creates a kernel and makes it possible for the rules to retrieve the kernel using a get() in the abstract class Whats the convention of passing around/creating kernels? Just create new kernels, or reuse them?

    Read the article

  • Rebinding and singleton-behaviour [NInject]

    - by Maximilian Csuk
    Hi! I have set up a NInject (using version 1.5) binding like this: Bind<ISessionFactory>().ToMethod<ISessionFactory>(ctx => { try { // create session factory, might fail because of database issues like wrong connection string } catch (Exception e) { throw new DatabaseException(e); } }).Using<SingletonBehavior>(); As you can see, this binding uses a singleton behavior but can also throw exception when something is not configured correctly, like a wrong connection string to the database. Now, when the creation of a session factory fails at first (throwing a database exception), NInject doesn't try to create the object again but always returns null. I would need NInject to check for null first and recreate when the instance is null, but of course not when there already is an instance successfully constructed (keeping it singleton). Like this: var a = Kernel.Get<ISessionFactory>(); // might fail, a = null // ... change some database settings var b = Kernel.Get<ISessionFactory>(); // might not fail anymore, b = ISessionFactory object Would I need to write a custom behavior or am I missing something else? Thanks for your answers!

    Read the article

  • Ninject: Singleton binding syntax?

    - by Rosarch
    I'm using Ninject 2.0 for the .Net 3.5 framework. I'm having difficulty with singleton binding. I have a class UserInputReader which implements IInputReader. I only want one instance of this class to ever be created. public class MasterEngineModule : NinjectModule { public override void Load() { // using this line and not the other two makes it work //Bind<IInputReader>().ToMethod(context => new UserInputReader(Constants.DEFAULT_KEY_MAPPING)); Bind<IInputReader>().To<UserInputReader>(); Bind<UserInputReader>().ToSelf().InSingletonScope(); } } static void Main(string[] args) { IKernel ninject = new StandardKernel(new MasterEngineModule()); MasterEngine game = ninject.Get<MasterEngine>(); game.Run(); } public sealed class UserInputReader : IInputReader { public static readonly IInputReader Instance = new UserInputReader(Constants.DEFAULT_KEY_MAPPING); // ... public UserInputReader(IDictionary<ActionInputType, Keys> keyMapping) { this.keyMapping = keyMapping; } } If I make that constructor private, it breaks. What am I doing wrong here?

    Read the article

  • How to use Ninject with XNA?

    - by Rosarch
    I'm having difficulty integrating Ninject with XNA. static class Program { /** * The main entry point for the application. */ static void Main(string[] args) { IKernel kernel = new StandardKernel(NinjectModuleManager.GetModules()); CachedContentLoader content = kernel.Get<CachedContentLoader>(); // stack overflow here MasterEngine game = kernel.Get<MasterEngine>(); game.Run(); } } // constructor for the game public MasterEngine(IKernel kernel) : base(kernel) { this.inputReader = kernel.Get<IInputReader>(); graphicsDeviceManager = kernel.Get<GraphicsDeviceManager>(); Components.Add(kernel.Get<GamerServicesComponent>()); // Tell the loader to look for all files relative to the "Content" directory. Assets = kernel.Get<CachedContentLoader>(); //Sets dimensions of the game window graphicsDeviceManager.PreferredBackBufferWidth = 800; graphicsDeviceManager.PreferredBackBufferHeight = 600; graphicsDeviceManager.ApplyChanges(); IsMouseVisible = false; } Ninject.cs: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Ninject.Modules; using HWAlphaRelease.Controller; using Microsoft.Xna.Framework; using Nuclex.DependencyInjection.Demo.Scaffolding; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; namespace HWAlphaRelease { public static class NinjectModuleManager { public static NinjectModule[] GetModules() { return new NinjectModule[1] { new GameModule() }; } /// <summary>Dependency injection rules for the main game instance</summary> public class GameModule : NinjectModule { #region class ServiceProviderAdapter /// <summary>Delegates to the game's built-in service provider</summary> /// <remarks> /// <para> /// When a class' constructor requires an IServiceProvider, the dependency /// injector cannot just construct a new one and wouldn't know that it has /// to create an instance of the Game class (or take it from the existing /// Game instance). /// </para> /// <para> /// The solution, then, is this small adapter that takes a Game instance /// and acts as if it was a freely constructable IServiceProvider implementation /// while in reality, it delegates all lookups to the Game's service container. /// </para> /// </remarks> private class ServiceProviderAdapter : IServiceProvider { /// <summary>Initializes a new service provider adapter for the game</summary> /// <param name="game">Game the service provider will be taken from</param> public ServiceProviderAdapter(Game game) { this.gameServices = game.Services; } /// <summary>Retrieves a service from the game service container</summary> /// <param name="serviceType">Type of the service that will be retrieved</param> /// <returns>The service that has been requested</returns> public object GetService(Type serviceType) { return this.gameServices; } /// <summary>Game services container of the Game instance</summary> private GameServiceContainer gameServices; } #endregion // class ServiceProviderAdapter #region class ContentManagerAdapter /// <summary>Delegates to the game's built-in ContentManager</summary> /// <remarks> /// This provides shared access to the game's ContentManager. A dependency /// injected class only needs to require the ISharedContentService in its /// constructor and the dependency injector will automatically resolve it /// to this adapter, which delegates to the Game's built-in content manager. /// </remarks> private class ContentManagerAdapter : ISharedContentService { /// <summary>Initializes a new shared content manager adapter</summary> /// <param name="game">Game the content manager will be taken from</param> public ContentManagerAdapter(Game game) { this.contentManager = game.Content; } /// <summary>Loads or accesses shared game content</summary> /// <typeparam name="AssetType">Type of the asset to be loaded or accessed</typeparam> /// <param name="assetName">Path and name of the requested asset</param> /// <returns>The requested asset from the the shared game content store</returns> public AssetType Load<AssetType>(string assetName) { return this.contentManager.Load<AssetType>(assetName); } /// <summary>The content manager this instance delegates to</summary> private ContentManager contentManager; } #endregion // class ContentManagerAdapter /// <summary>Initializes the dependency configuration</summary> public override void Load() { // Allows access to the game class for any components with a dependency // on the 'Game' or 'DependencyInjectionGame' classes. Bind<MasterEngine>().ToSelf().InSingletonScope(); Bind<NinjectGame>().To<MasterEngine>().InSingletonScope(); Bind<Game>().To<MasterEngine>().InSingletonScope(); // Let the dependency injector construct a graphics device manager for // all components depending on the IGraphicsDeviceService and // IGraphicsDeviceManager interfaces Bind<GraphicsDeviceManager>().ToSelf().InSingletonScope(); Bind<IGraphicsDeviceService>().To<GraphicsDeviceManager>().InSingletonScope(); Bind<IGraphicsDeviceManager>().To<GraphicsDeviceManager>().InSingletonScope(); // Some clever adapters that hand out the Game's IServiceProvider and allow // access to its built-in ContentManager Bind<IServiceProvider>().To<ServiceProviderAdapter>().InSingletonScope(); Bind<ISharedContentService>().To<ContentManagerAdapter>().InSingletonScope(); Bind<IInputReader>().To<UserInputReader>().InSingletonScope().WithConstructorArgument("keyMapping", Constants.DEFAULT_KEY_MAPPING); Bind<CachedContentLoader>().ToSelf().InSingletonScope().WithConstructorArgument("rootDir", "Content"); } } } } NinjectGame.cs /// <summary>Base class for Games making use of Ninject</summary> public class NinjectGame : Game { /// <summary>Initializes a new Ninject game instance</summary> /// <param name="kernel">Kernel the game has been created by</param> public NinjectGame(IKernel kernel) { Type ownType = this.GetType(); if(ownType != typeof(Game)) { kernel.Bind<NinjectGame>().To<MasterEngine>().InSingletonScope(); } kernel.Bind<Game>().To<NinjectGame>().InSingletonScope(); } } } // namespace Nuclex.DependencyInjection.Demo.Scaffolding When I try to get the CachedContentLoader, I get a stack overflow exception. I'm basing this off of this tutorial, but I really have no idea what I'm doing. Help?

    Read the article

  • Deploying MVC2 application to IIS7.5 - Ninject asked to provide controllers for content files

    - by Rune Jacobsen
    I have an application that started life as an MVC (1.0) app in Visual Studio 2008 Sp1 with a bunch of Silverlight 3 projects as part of the site. Nothing fancy at all. Using Ninject for dependency injection (first version 2 beta, now the released version 2 with the MVC extensions). With the release of .Net 4.0, VS2010, MVC2 etc., we decided to move the application to the newest platform. The conversion wizard in VS2010 apparently took care of everything, with one exception - it didn't change references to mvc1 to now point to mvc2, so I had to do that manually. Of course, this makes me think about other MVC2 things that could be missing from my app, that would be there if I did File - New Project... But that is not the focus of this question. When I deploy this application to the IIS 7.5 server (running on Win2008 R2 x64), the application as such works. However, images, scripts and other static content doesn't seem to exist. Of course they are there on disk on the server, but they don't show up in the client web browser. I am fairly new to IIS, so the only trick I knew is to try to open the web page in a browser on the server, as that could give me more information. And here, finally, we meet our enemy. If I try to go directly to the URL of one of the images (http://server/Content/someimage.jpg for instance), I get the following error in the browser: The IControllerFactory 'Ninject.Web.Mvc.NinjectControllerFactory' did not return a controller for a controller named 'Content'. Aha. The web server tries to feed this request to MVC, who with its' default routing setup assumes Content to be a controller, and fails. How can I get it to treat Content/ and Scripts/ (among others) as non-controllers and just pass through the static content? This of course works with Cassini on my developer machine, but as soon as I deploy, this problem hits. I am using the last version of Ninject MVC 2 where the IoC tool should pass missing controllers to the base controller factory, but this has apparently not helped. I have also tried to add ignore routes for Content etc., but this apparently has no effect either. I am not even sure I am addressing the problem on the right level. Does anyone know where to look to get this app going? I have full control of the web server so I can more or less do whatever I want to it, as long as it starts working. Thanks!

    Read the article

  • Does NInject work in medium trust hosting?

    - by Gabriel
    I'm doing shared hosting with GoDaddy and I developed a sample ASP.NET MVC app using Castle Windsor and unfortunately, it didn't work in a medium trust setting. Specifically, I got this error: "[SecurityException: That assembly does not allow partially trusted callers"... etc. GoDaddy is sadly not flexible in their trust policy. I'm not tied to Windsor and would like to try another one that will work under Medium Trust. I'd actually like to use NInject, but I've read people having mixed success. The only one I've read that works with no problem is Microsoft's Unity. My question is, does NInject work in medium trust? If not, what are my options?

    Read the article

  • Solving a cyclical dependency in Ninject (Compact Framework)

    - by Alex
    I'm trying to use Ninject for dependency injection in my MVP application. However, I have a problem because I have two types that depend on each other, thus creating a cyclic dependency. At first, I understand that it was a problem, because I had both types require each other in their constructors. Therefore, I moved one of the dependencies to a property injection instead, but I'm still getting the error message. What am I doing wrong? This is the presenter: public class LoginPresenter : Presenter<ILoginView>, ILoginPresenter { public LoginPresenter( ILoginView view ) : base( view ) { } } and this is the view: public partial class LoginForm : Form, ILoginView { [Inject] public ILoginPresenter Presenter { private get; set; } public LoginForm() { InitializeComponent(); } } And here's the code that causes the exception: static class Program { /// <summary> /// The main entry point for the application. /// </summary> [MTAThread] static void Main() { // Show the login form Views.LoginForm loginForm = Kernel.Get<Views.Interfaces.ILoginView>() as Views.LoginForm; Application.Run( loginForm ); } } The exception happens on the line with the Kernel.Get<>() call. Here it is: Error activating ILoginPresenter using binding from ILoginPresenter to LoginPresenter A cyclical dependency was detected between the constructors of two services. Activation path: 4) Injection of dependency ILoginPresenter into property Presenter of type LoginForm 3) Injection of dependency ILoginView into parameter view of constructor of type LoginPresenter 2) Injection of dependency ILoginPresenter into property Presenter of type LoginForm 1) Request for ILoginView Suggestions: 1) Ensure that you have not declared a dependency for ILoginPresenter on any implementations of the service. 2) Consider combining the services into a single one to remove the cycle. 3) Use property injection instead of constructor injection, and implement IInitializable if you need initialization logic to be run after property values have been injected. Why doesn't Ninject understand that since one is constructor injection and the other is property injection, this can work just fine? I even read somewhere looking for the solution to this problem that Ninject supposedly gets this right as long as the cyclic dependency isn't both in the constructors. Apparently not, though. Any help resolving this would be much appreciated.

    Read the article

  • Ninject 2 and MVC 2.0

    - by theouteredge
    I've updated a project to VS2010 and MVC2 from VS2008 and MVC1. I'm having problems with Ninject not finding controllers within Areas Here is my global.asax.cs file: namespace Website { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : NinjectHttpApplication { public static StandardKernel NinjectKernel; public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Balance", "Balance/{action}/{month}/{year}", new { controller = "Balance", action = "Index", month = DateTime.Now.Month, year = DateTime.Now.Year } ); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Login", action = "Index", id = "" } // Parameter defaults ); } /* protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); // initializes the NHProfiler so you can see what is going on with your queries HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize(); } */ protected override void OnApplicationStarted() { RegisterRoutes(RouteTable.Routes); AreaRegistration.RegisterAllAreas(); RegisterAllControllersIn(Assembly.GetExecutingAssembly()); } protected void Application_Error(object sender, EventArgs e) { var errorService = NinjectKernel.Get<IErrorLogService>(); errorService.LogError(HttpContext.Current.Server.GetLastError().GetBaseException(), "AppSite"); } protected override IKernel CreateKernel() { if (NinjectKernel == null) { NinjectKernel = new StandardKernel(new ServiceModule()); } return NinjectKernel; } } public class ServiceModule : NinjectModule { public override void Load() { Bind<IHelper>().To<Helper>().InRequestScope(); Bind<IErrorLogService>().To<ErrorLogService>(); Bind<INHSessionFactory>().To<NHSessionFactory>().InSingletonScope(); Bind<ISessionFactory>().ToMethod(ctx => ctx.Kernel.Get<INHSessionFactory>().GetSessionFactory()) .InSingletonScope(); Bind<INHSession>().To<NHSession>(); Bind<ISession>().ToMethod(ctx => ctx.Kernel.Get<INHSession>().GetSession()); } } } Accessing controllers within the /Controllers folder works OK, but accessing controllers within a /Areas/Member/Controller throws the following error: Server Error in '/' Application. Cannot be null Parameter name: service 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.ArgumentNullException: Cannot be null Parameter name: service 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: [ArgumentNullException: Cannot be null Parameter name: service] Ninject.ResolutionExtensions.GetResolutionIterator(IResolutionRoot root, Type service, Func`2 constraint, IEnumerable`1 parameters, Boolean isOptional, Boolean isUnique) +193 Ninject.Web.Mvc.NinjectControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +41 System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +66 System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +124 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +50 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8771488 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184 Version Information: Microsoft .NET Framework Version:4.0.30128; ASP.NET Version:4.0.30128.1 The Url for this request is /Member/Controller/, If I change the Url too /Controller the controller fires but I get an error that the system cannot find the View in the path /Views When it should be looking in /Area/Members/Views I have either done something wrong in the upgrade or I'm missing something bt I just can't figure out what. I've been trying to figure this out for 3 days...

    Read the article

  • Ninject WithConstructorArgument : No matching bindings are available, and the type is not self-bindable

    - by Jean-François Beauchamp
    My understanding of WithConstructorArgument is probably erroneous, because the following is not working: I have a service, lets call it MyService, whose constructor is taking multiple objects, and a string parameter called testEmail. For this string parameter, I added the following Ninject binding: string testEmail = "[email protected]"; kernel.Bind<IMyService>().To<MyService>().WithConstructorArgument("testEmail", testEmail); However, when executing the following line of code, I get an exception: var myService = kernel.Get<MyService>(); Here is the exception I get: Error activating string No matching bindings are available, and the type is not self-bindable. Activation path: 2) Injection of dependency string into parameter testEmail of constructor of type MyService 1) Request for MyService Suggestions: 1) Ensure that you have defined a binding for string. 2) If the binding was defined in a module, ensure that the module has been loaded into the kernel. 3) Ensure you have not accidentally created more than one kernel. 4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name. 5) If you are using automatic module loading, ensure the search path and filters are correct. What am I doing wrong here? UPDATE: Here is the MyService constructor: [Ninject.Inject] public MyService(IMyRepository myRepository, IMyEventService myEventService, IUnitOfWork unitOfWork, ILoggingService log, IEmailService emailService, IConfigurationManager config, HttpContextBase httpContext, string testEmail) { this.myRepository = myRepository; this.myEventService = myEventService; this.unitOfWork = unitOfWork; this.log = log; this.emailService = emailService; this.config = config; this.httpContext = httpContext; this.testEmail = testEmail; } I have standard bindings for all the constructor parameter types. Only 'string' has no binding, and HttpContextBase has a binding that is a bit different: kernel.Bind<HttpContextBase>().ToMethod(context => new HttpContextWrapper(new HttpContext(new MyHttpRequest("", "", "", null, new StringWriter())))); and MyHttpRequest is defined as follows: public class MyHttpRequest : SimpleWorkerRequest { public string UserHostAddress; public string RawUrl; public MyHttpRequest(string appVirtualDir, string appPhysicalDir, string page, string query, TextWriter output) : base(appVirtualDir, appPhysicalDir, page, query, output) { this.UserHostAddress = "127.0.0.1"; this.RawUrl = null; } }

    Read the article

  • Ninject with Object Initializers and LINQ

    - by Alexander Kahoun
    I'm new to Ninject so what I'm trying may not even be possible but I wanted to ask. I free-handed the below so there may be typos. Let's say I have an interface: public interface IPerson { string FirstName { get; set; } string LastName { get; set;} string GetFullName(); } And a concrete: public class Person : IPerson { public string FirstName { get; set; } public string LastName { get; set; } public string GetFullName() { return String.Concat(FirstName, " ", LastName); } } What I'm used to doing is something like this when I'm retrieving data from arrays or xml: public IEnumerable<IPerson> GetPeople(string xml) { XElement persons = XElement.Parse(xml); IEnumerable<IPerson> people = ( from person in persons.Descendants("person") select new Person { FirstName = person.Attribute("FName").Value, LastName = person.Attribute("LName").Value }).ToList(); return people; } I don't want to tightly couple the concrete to the interface in this manner. I haven't been able to find any information in regards to using Ninject with LINQ to Objects or with object initializers. I may be looking in the wrong places, but I've been searching for a day now with no luck at all. I was contemplating putting the kernel into an singleton instance and seeing if that would work, but I'm not sure that it will plus I've heard that passing your kernel around is a bad thing. I'm trying to implement this in a class library currently. If this is not possible, does anyone have any examples or suggestions as to what the best practice is in this case? Thanks in advance for the help. EDIT: Based on some of the answers I feel I should clarify. Yes, the example above appears short lived but it was simply an example of one piece that I was trying to do. Let's give a bigger picture. Say instead of XML I am gathering all my data through a 3rd party web service and I'm creating an interface for it, the data could be a defined object in the wsdl or it could sometimes be an xml string. IPerson could be used for both the Person object and a User object. I will be doing this inside of a separate class library, because it needs to be portable and will be used in other projects, and handing it to an MVC3 Web Application and the objects will be used in javascript as well. I appreciate all the input so far.

    Read the article

  • Ninject: Controller Constructor with int argument

    - by Fleents
    How can you instantiate a Controller that has an int argument? Using Ninject.. My HomeController has a constructor like this: private int _masterId; Public HomeController(int masterId){ _masterId = masterId; } I created a controller factory like this: public class NinjectControllerFactory : DefaultControllerFactory { IKernel kernel = new StandardKernel(new ExampleConfigModule()); protected override IController GetControllerInstance(Type controllerType) { return controllerType == null ? null : (IController)kernel.Get(controllerType, 1); } }

    Read the article

  • Ninject - initialise objects

    - by James Lin
    Hi guys, I am new to ninject, I am wondering how I can run custom initizlisation code when constructing the injected objects? ie. I have a Sword class which implements IWeapon, but I want to pass an hit point value to the Sword class constructor, how do I achieve that? Do I need to write my own provider? A minor question, IKernel kernel = new StandardKernel(new Module1(), new Module2(), ...); what is the actual use of having multiple modules in Kernel? I sorta understand it, but could someone give me a formal explaination and use case? Thanks a lot! James

    Read the article

  • Using ninject/autofac for a given scenario

    - by sandesh247
    I have some providers, say - <Providers> <Provider Type="Providers.IM" Name="Im"/> <Provider Type="Providers.Web" Name="Web"/> ... </Provider> Each of these providers can give me a session : <Sessions> <Session Name="GoogleIM" Provider="Im" URL="..." /> <Session Name="YahooIM" Provider="Im" URL="..." /> <Session Name="YahooWeb" Provider="Web" URL="..." /> ... </Session> Currently, I instantiate "named" sessions by looking at the provider, instantiating the type, and injecting the URL (manually). I could use a session factory, which would probably have to understand the url and return a proper session. Is there a way to handle this more elegantly/simply with ninject/autofac?

    Read the article

  • Can I use Ninject ConstructorArguments with strong naming?

    - by stiank81
    Well, I don't know if "strong naming" is the right term, but what I want to do is as follows. Currently I use ConstructorArgument like e.g. this: public class Ninja { private readonly IWeapon _weapon; private readonly string _name; public Ninja(string name, IWeapon weapon) { _weapon = weapon; _name = name; } // ..more code.. } public void SomeFunction() { var kernel = new StandardKernel(); kernel.Bind<IWeapon>().To<Sword>(); var ninja = ninject.Get<Ninja>(new ConstructorArgument("name", "Lee")); } Now, if I rename the parameter "name" (e.g. using ReSharper) the ConstructorArgument won't update, and I will get a runtime error when creating the Ninja. To fix this I need to manually find all places I specify this parameter through a ConstructorArgument and update it. No good, and I'm doomed to fail at some point even though I have good test coverage. Renaming should be a cheap operation. Is there any way I can make a reference to the parameter instead - such that it is updated when I rename the parameter?

    Read the article

  • Parameter based bindings in ninject 2.0

    - by Przemaas
    I want to use conditional binding in ninject, based on passed parameters. I have something like below: public class Subject { } public interface ITarget { } public class Target1 : ITarget { } public class Target2 : ITarget { } And now I need to instantiate ITarget interface: public void MethodName(IKernel kernel) { ITarget target1 = kernel.Get<ITarget>(new Parameter("name", new Subject(), true)); // Should be instance of Target1 ITarget target2 = kernel.Get<ITarget>(); // Should be instance of Target2 } I have problems to define proper bindings. I tried the following: kernel.Bind<ITarget>().To<Target1>().When(Predicate); kernel.Bind<ITarget>().To<Target2>(); private bool Predicate(IRequest request) { IParameter parameter = request.Parameters.Count == 0 ? null : request.Parameters[0]; if (parameter == null) { return false; } object parameterValue = parameter.GetValue( /*what to put here?*/); return parameterValue != null && parameterValue.GetType().IsAssignableFrom(typeof(Subject)); } but I don't know how to get value of passed parameter. I need to pass IContext instance to GetValue method, but don't know how to get valid instance of IContext. Or maybe there is better way to accomplish my task? Regards

    Read the article

  • Ninject problem binding to constant value in MVC3 with a RavenDB session

    - by Jim
    I've seen a lot of different ways of configuring Ninject with ASP.NET MVC, but the implementation seems to change slightly with each release of the MVC framework. I'm trying to inject a RavenDB session into my repository. Here is what I have that's almost working. public class MvcApplication : NinjectHttpApplication { ... protected override void OnApplicationStarted() { base.OnApplicationStarted(); AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); } protected override IKernel CreateKernel() { return new StandardKernel(new MyNinjectModule()); } public static IDocumentSession CurrentSession { get { return (IDocumentSession)HttpContext.Current.Items[RavenSessionKey]; } } ... } public class MyNinjectModule : NinjectModule { public override void Load() { Bind<IUserRepository>().To<UserRepository>(); Bind<IDocumentSession>().ToConstant(MvcApplication.CurrentSession); } } When it tries to resolve IDocumentSession, I get the following error. Error activating IDocumentSession using binding from IDocumentSession to constant value Provider returned null. Activation path: 3) Injection of dependency IDocumentSession into parameter documentSession of constructor of type UserRepository Any ideas on how to make the IDocumentSession resolve?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8  | Next Page >