简体   繁体   中英

LightInject GetInstance returning that cannot be used with type arguments

I'm new to dependency injection and I find LightInject to start. So I created 2 interfaces and implemented those interfaces into 2 classes. Now, I want to get a instance of Payment but compiler keeps saying that non-generic method 'ServiceContainer.GetInstance(Type) cannot be used with type arguments.

My interfaces are implemented in different files. I tried the way this guys says ( Getting Started with LightInject ) and works fine. But I think, somehow, as my interfaces and classes are in different files, it's not working i dont know why.

My codes are like this. IContract

namespace ConsoleApp1.Interfaces
{
    public interface IContract
    {
        int Discount();
    }
}

IPayment:

namespace ConsoleApp1.Interfaces
{
    public interface IPayment
    {
        void Pay();
    }
}

CrazyContract:

namespace ConsoleApp1.Classes
{
    public class CrazyContract: IContract
    {
        public int Discount()
        {
            return 3;
        }
    }
}

Payment and more important classe:

namespace ConsoleApp1.Classes
{
    public class Payment: IPayment
    {
        private readonly IContract _contract;

        public Payment(IContract contract)
        {
            _contract = contract;
        }

        public void Pay()
        {
            Console.WriteLine("Discount {0}", _contract.Discount());
        }
    }
}

and my main which returns the error:

using ConsoleApp1.Classes;
using ConsoleApp1.Interfaces;
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var container = new LightInject.ServiceContainer();

            container.Register<IPayment, Payment>();
            container.Register<IContract, CrazyContract>();

            var p = container.GetInstance<IPayment>(); // the error is here

        }
    }
}

and the error:

error CS0308: The non-generic method 'ServiceContainer.GetInstance(Type)' cannot be used with type arguments

As you guys can see, I'm using Constructor Injection and I'd be very happy if any of you could explain what I'm doing wrong. Thank you!

I find a way to fix the problem.

We should explicitly that we need the package LightInject.

So, just put this code

using LightInject;

I dont really know why but this works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM