autofac 基类属性为 null

发布于 2025-01-05 20:11:51 字数 1067 浏览 1 评论 0原文

这是我对 Asp.Net Mvc 3 的设置:

public abstract class BaseProvider
{
    protected ICache Cache;
}

public interface ICache
{
    void Add(string key, object data);
    void Remove(string key);
    ...
}

public class MyCache : ICache
{
    private static MemoryCache cache = MemoryCache.Default;
    void Add(string key, object data)
    {
    ...
    }
}

public interface IEmployeeProvider
{
    IEnumerable<Employee> GetEmployees(string department);
}

public class EmployeeProvider:BaseProvider,IEmployeeProvider
{
    public IEnumerable<Employee> GetEmployees(string department)
    {
         **if (Cache.Get("employees_"+department)!=null)**

    }
}

加星号的行抛出一个错误,指出 Cache 为空。 我尝试将基类注册为类型,但是我想这是错误的。 我的 Autofac 设置是这样的:

builder.Register(r => new EmployeeProvider()).As<IEmployeeProvider>().InstancePerHttpRequest();
builder.Register(r => new MyCache()).As<ICache>().InstancePerHttpRequest();
builder.RegisterType<BaseProvider>().PropertiesAutowired();

我缺少什么?

Here is my setup with Asp.Net Mvc 3:

public abstract class BaseProvider
{
    protected ICache Cache;
}

public interface ICache
{
    void Add(string key, object data);
    void Remove(string key);
    ...
}

public class MyCache : ICache
{
    private static MemoryCache cache = MemoryCache.Default;
    void Add(string key, object data)
    {
    ...
    }
}

public interface IEmployeeProvider
{
    IEnumerable<Employee> GetEmployees(string department);
}

public class EmployeeProvider:BaseProvider,IEmployeeProvider
{
    public IEnumerable<Employee> GetEmployees(string department)
    {
         **if (Cache.Get("employees_"+department)!=null)**

    }
}

Starred line throws an error saying that Cache is null.
I tried to register the base class as a type but, I guess it is wrong.
My Autofac setup is like this:

builder.Register(r => new EmployeeProvider()).As<IEmployeeProvider>().InstancePerHttpRequest();
builder.Register(r => new MyCache()).As<ICache>().InstancePerHttpRequest();
builder.RegisterType<BaseProvider>().PropertiesAutowired();

What am I missing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

够运 2025-01-12 20:11:51

您应该使用 PropertiesAutowired() 注册 EmployeeProvider 或扫描程序集以查找从 BaseProvider 继承的每个类。

第一个注册忘记了 PropertiesAutowired(),第三行忘记了 EmployeeProvider

You should either register EmployeeProvider with PropertiesAutowired() or scan the assembly for every class that inherits from BaseProvider.

The first registration forgets the PropertiesAutowired(), the third line forgets the EmployeeProvider.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文