实现接口以在应用程序启动时运行代码

时间:2014-04-26 11:50:12

标签: c# asp.net-mvc

对于遇到麻烦的人抱歉,我在这里将其改为一个新问题:MVC: Run a method on Application startup without calling it from Application_Start


这可能是一个非常简单的问题,但是使用方法OnStartup建立接口的最佳方法是什么。实现此接口后,OnStartup()代码应在application_start上运行。

编辑:我正在尝试创建一个HttpModule或类似的东西,当我实现这个模块的特定类时,这个类将有一个方法,并通过重写这个方法,我将能够在应用程序启动时运行它的代码

我唯一的问题是我不想直接从application_start方法调用任何代码。

P.S。如果有可用的nuget包,请告诉我名称。

4 个答案:

答案 0 :(得分:1)

您无法通过实现界面来运行任何代码,只需强制您的类实现OnStartup方法的代码

interface IOnStartup
{
    void OnStartup();
}

class MyClass : IOnStartup
{
    public void OnStartup()
    {
       // your code for OnStartUp method
       // you are forced to implement the code for this method because your class implement IOnStartup
    }
}

或者您可以定义一个实现此代码的抽象类,并从该抽象类继承应该具有该方法的所有类。

abstract class OnStartUpClass
{
    public void OnStartup()
    {
        // the code for this method
    }
}

class MyClass : OnStartUpClass
{
    // implement code for this class
    // you already have this method in your class
}

我认为通过实现接口无法实现您想要做的事情。你应该选择另一种方式来做到这一点。

答案 1 :(得分:1)

定义您的界面和类:

interface IOnStartup
{
    void OnStartup();
}

class YourClass : IOnStartup
{
    public void OnStartup()
    {
    }
}

添加Global.asax

public void Application_OnStart() 
{
    var cls = new YourClass();
    cls.OnStartup();
}

答案 2 :(得分:1)

如果我理解正确,如果有一个实现给定接口的类,则希望实例化该类并调用它的OnStartup方法。如果这是你想要做的事情,那么你必须依靠反思。

在Application_Start中调用一个方法,该方法将加载程序集中存在的所有类型,并检查它们中是否有任何类型实现了该接口。如果找到,您可以实例化它的实例并在该类上调用该方法。

如果要动态添加类而不重新编译自己的应用程序,那么它会变得更加复杂,并且涉及创建AppDomains,但它也是可行的。

修改

stackoverflow上的这个问题告诉你如何获得实现接口的所有类:

Getting all types that implement an interface

答案 3 :(得分:0)

我会使用像Autofac,Ninject,Unity这样的IOC容器。然后,您可以使用框架注册接口,并使用服务定位器返回实现该接口的所有类实例。

//using Autofac
var builder = new ContainerBuilder();
containerBuilder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
                            .AsImplementedInterfaces()
                            .InstancePerLifetimeScope();

var container = builder.Build();
var myItems = Container.Resolve<ISomeInterface>();

foreach(var item in myItems){
    item.DoSomething()
}