Pages

Monday, June 4, 2018

Ninject Setup IoC and Webapi

Ninject Setup IoC and Webapi
Namespace

  • Ninject.Mvc5
  • Ninject.Web.WebApi
  • Ninject.Web.Common.WebHost
  • Ninject.Web.Common
  • Ninject
  • WebActivatorEx


Ninject.Mvc5 installs dependencies

  • Ninject.Web.Common.WebHost
  • Ninject.Web.Common
  • Ninject.Web.Mvc
  • Ninject

Making Ninject work with WebApi
Installing package
  • Ninject.Web.WebApi

Will add dependency
  • Ninject.Web.WebApi
Making Ninject auto executing
Install package
  • WebActivatorEx
Below, file was created in App_Start or manually created


[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(YooperGreens.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(YooperGreens.App_Start.NinjectWebCommon), "Stop")]

namespace YooperGreens.App_Start
{
    using System;
    using System.Web;
    using System.Web.Http;
    using Microsoft.Web.Infrastructure.DynamicModuleHelper;

    using Ninject;
    using Ninject.Web.Common;
    using Ninject.Web.Common.WebHost;
    using Ninject.Web.WebApi;
    using YooperGreens.Db;

    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();
            try
            {
                kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
                kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

                RegisterServices(kernel);
                GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
                return kernel;
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }

        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind<YooperGreensDbContext>().ToSelf().InRequestScope();
            kernel.Bind<IAccountViewModel>().To<AccountViewModel>();
        }
    }
}

This post is for the purpose of my notes only and sometimes a rant.
“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”
Henry Ford

Missing System.Web.Http namespace

Quick fix

Within Visual Studio package manager enter,

Update-Package -reinstall Microsoft.AspNet.WebApi.Core


This post is for the purpose of my notes only and sometimes a rant.
“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”
Henry Ford

Sunday, June 3, 2018

Entityframework 6.2 Model Confuguration / Seed Initializer

Install package

  • Install-Package EntityFramework

Create Model Class

    public class Seed
    {
        public Guid SeedId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public string Link { get; set; }
        public Germination Germination { get; set; }
        public string Supplier { get; set; }
        public int Count { get; set; }
        public decimal Price { get; set; }

        public ICollection<Order> Orders { get; set; }
    }

    public class Order
    {
        public Guid OrderId { get; set; }
        public decimal Shipping { get; set; }
        public decimal Tax { get; set; }
        public Seed Seed { get; set; }

    }
Create DbContext Class

    public interface IYooperGreensDbContext
    {
        DbSet<Seed> Seeds { get; set; }
        DbSet<Order> Orders { get; set; }

    }

    public class YooperGreensDbContext : DbContext, IYooperGreensDbContext
    {
        public YooperGreensDbContext()
            :base("yoopergreens")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            ModelConfiguration configuration = new ModelConfiguration();

            modelBuilder.Configurations.Add(configuration.Seed);
            modelBuilder.Configurations.Add(configuration.Order);

        }
        public DbSet<Seed> Seeds { get; set; }
        public DbSet<Order> Orders { get; set; }
    }

Create Configuration Classes for each model class

    public class OrderConfiguration: EntityTypeConfiguration<Order>
    {
        public OrderConfiguration()
        {
            HasKey(o => o.OrderId);
            HasRequired(o => o.Seed).WithMany(o => o.Orders);
        }
    }

    public class SeedConfiguration : EntityTypeConfiguration<Seed>
    {
        public SeedConfiguration()
        {
            HasKey(s => s.SeedId);
        }
    }

Create Centralized Configuration file

     public class ModelConfiguration
    {
        public SeedConfiguration Seed { get { return new SeedConfiguration(); } }
        public OrderConfiguration Order { get { return new OrderConfiguration(); } }
    }

Create a custom DB initializer to seed data into database:

  • CreateDatabaseIfNotExists
  • DropCreateDatabaseIfModelChanges
  • DropCreateDatabaseAlways


    public class YooperGreensDbInitializer : DropCreateDatabaseAlways<YooperGreensDbContext>
    {
        public YooperGreensDbInitializer()
        {
        }

        protected override void Seed(YooperGreensDbContext context)
        {

            IList<Seed> seeds = new List<Seed>
            {
                new Seed {}
            };

            context.Seeds.AddRange(seeds);

            base.Seed(context);
        }
    }

Set this DB initializer class in context class's constructor


        public YooperGreensDbContext()
            :base("yoopergreens")
        {
            Database.SetInitializer(new YooperGreensDbInitializer());

            Configuration.ProxyCreationEnabled = false;

        }

File Structure



This post is for the purpose of my notes only and sometimes a rant.
“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”
Henry Ford