Bar*_*ğlu 15 .net c# dependency-injection autofac
我只是尝试使用AutoFac来解决依赖关系,但它会抛出异常,例如
请求的服务"ProductService"尚未注册.要避免此异常,请注册组件以提供服务或使用IsRegistered()...
class Program
{
static void Main(string[] args)
{
var builder = new ContainerBuilder();
builder.RegisterType<ProductService>().As<IProductService>();
using (var container = builder.Build())
{
container.Resolve<ProductService>().DoSomething();
}
}
}
public class ProductService : IProductService
{
public void DoSomething()
{
Console.WriteLine("I do lots of things!!!");
}
}
public interface IProductService
{
void DoSomething();
}
Run Code Online (Sandbox Code Playgroud)
我做错了什么?
nem*_*esv 30
声明:
builder.RegisterType<ProductService>().As<IProductService>();
Run Code Online (Sandbox Code Playgroud)
每当有人试图解决IProductService给他们时,告诉AutofacProductService
所以你需要解决IProductService以下问题ProductService:
using (var container = builder.Build())
{
container.Resolve<IProductService>().DoSomething();
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您想将其Resolve<ProductService>注册到AsSelf:
builder.RegisterType<ProductService>().AsSelf();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23198 次 |
| 最近记录: |